通常我们用 frame 进行button 的这样排列 很容易,这次心血来潮用Massonry来进行这样的约束
//记录上一个按钮
UIButton *lastBUtton = nil;
for (int i = 0; i < 8; i++) {
XBButton *button = [XBButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
button.adjustsImageWhenHighlighted = NO;
NSArray *dictArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"shops" ofType:@"plist"]];
NSMutableArray *shopArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
HomeShop *shop = [HomeShop shopWithDict:dict];
[shopArray addObject:shop];
}
button.shop = shopArray[i];
button.titleLabel.font = [UIFont systemFontOfSize:11];
[button setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
button. contentHorizontalAlignment =UIControlContentHorizontalAlignmentCenter;
[buttonView addSubview:button];
[button mas_makeConstraints:^(MASConstraintMaker *make) {
//设置高度
make.height.offset(60.0f);
float colTop = (10 + i/4 * 70.0f);
make.top.offset(colTop);
//当是 左边一列的时候 都是 距离父视图 向左边 10的间隔
if (i%4 == 0) {
make.left.offset(10.0f);
// make.width.offset(50.0f);
}else{
//当时中间列的时候 在上一个UIlabel的右边 添加10个 距离 并且设置等高
make.width.equalTo(lastBUtton.mas_width);
make.left.equalTo(lastBUtton.mas_right).offset(10.0f);
}
//当是 最右边列的时候 距离右边父视图的 距离为20 因为是向左所以是-20 控制底部也是 负数!!
if (i%4 == 3) {
make.right.offset(-10.0f);
}
}];
lastBUtton = button;
}
我这按钮 图片在上 文字在下 是自定义的按钮 自己写一个类 继承UIButton
-(void)layoutSubviews{
[super layoutSubviews];
// 调整图片
self.imageView.y = 0;
self.imageView.width = 40 ;
self.imageView.height = 40;
self.imageView.centerX = self.width/2;
// 调整文字
self.titleLabel.y = CGRectGetMaxY(self.imageView.frame);
self.titleLabel.width = self.width;
self.titleLabel.height = self.height - self.imageView.height;
self.titleLabel.centerX = self.imageView.centerX ;
}
这个self.imageView.centerX self.titleLabel.centerX
的 赋值一定要在height
的后面,否则会出现 当你点击button
的时候 图片会向左偏移
不点击的时候 显示正常
也就是这种情况
网友评论