/** * 创建方块view.m */ - (void)createSquares:(NSArray *)sqaures { // 一行最多4列 int maxCols = 4; // 宽度和高度 CGFloat buttonW = DQScreenW / maxCols; CGFloat buttonH = buttonW; for (int i = 0; i<sqaures.count; i++) { // 创建按钮 DQSqaureButton *button = [DQSqaureButton buttonWithType:UIButtonTypeCustom]; // 监听点击 [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside]; // 传递模型 button.square = sqaures[i]; [self addSubview:button]; // 计算frame int col = i % maxCols; int row = i / maxCols; button.x = col * buttonW; button.y = row * buttonH; button.width = buttonW; button.height = buttonH; //计算高度方式一(每创建一个就计算一次高度) //self.height = CGRectGetMaxY(button.frame); } //计算总行数方式一 start // 8个方块, 每行显示4个, 计算行数 8/4 == 2 2 // 9个方块, 每行显示4个, 计算行数 9/4 == 2 3 // 7个方块, 每行显示4个, 计算行数 7/4 == 1 2 // 总行数 能整除就取结果,不能整除就取结果+1 // NSUInteger rows = sqaures.count / maxCols; // if (sqaures.count % maxCols) { // 不能整除, + 1 // rows++; // } //计算总行数方式一 end //计算总行数方式二 // 总页数 == (总个数 + 每页的最大数 - 1) / 每页最大数 NSUInteger rows = (sqaures.count + maxCols - 1) / maxCols; // 计算footer的高度方式二 self.height = rows * buttonH; // 重绘 [self setNeedsDisplay]; }
//自定义的DQSqaureButton - (void)setup { self.titleLabel.textAlignment = NSTextAlignmentCenter; [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; self.titleLabel.font = [UIFont systemFontOfSize:15]; [self setBackgroundImage:[UIImage imageNamed:@"mainCellBackground"] forState:UIControlStateNormal]; } - (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { [self setup]; } return self; } - (void)awakeFromNib { [self setup]; } - (void)layoutSubviews { [super layoutSubviews]; // 调整图片 self.imageView.y = self.height * 0.15; self.imageView.width = self.width * 0.5; self.imageView.height = self.imageView.width; self.imageView.centerX = self.width * 0.5; // 调整文字 self.titleLabel.x = 0; self.titleLabel.y = CGRectGetMaxY(self.imageView.frame); self.titleLabel.width = self.width; self.titleLabel.height = self.height - self.titleLabel.y; } - (void)setSquare:(DQSquare *)square { _square = square; [self setTitle:square.name forState:UIControlStateNormal]; // 利用SDWebImage给按钮设置image [self sd_setImageWithURL:[NSURL URLWithString:square.icon] forState:UIControlStateNormal]; }
时间: 2024-11-03 21:55:18