我现在想自定义一个控件, 该控件初始化的时候会传入一个数组,我需要根据数组的个数创建若干个UIButton
button
的宽度是根据控件的宽度和各button
的间距算出来的, button
之间等间距..
请问这种情况如何用masonry
来布局这些button
? (这个控件也需要用Masonry
进行约束, 所以不会给它的frame
赋值)
我将我使用masonry
前后的代码贴了出来, 关键点height
和width
我用问好代替了,希望大神们能够赐教!
不使用masonry
是这样布局 :
- (instancetype)initWithFrame:(CGRect)frame items:(NSArray<NSString *> *)items
{
if (self = [super initWithFrame:frame]) {
self.backgroundColor = YZ_WhiteColor;
NSInteger count = items.count;
for (int i = 0; i < count; i++) {
NSInteger width = (self.bounds.size.width - margin * 2 - (count - 1) * gap) / count;
NSInteger height = btnHeight;
NSInteger x = margin + i * (gap + width);
NSInteger y = 10;
UIButton *btn = [self buttonForToolBarWithTitle:items[i]];
btn.frame = CGRectMake(x, y, width, height);
btn.tag = 100 + i;
btn.layer.cornerRadius = 5;
}
}
return self;
}
使用masonry
布局 :
- (instancetype)initWithFrame:(CGRect)frame items:(NSArray<NSString *> *)items
{
if (self = [super initWithFrame:frame]) {
self.backgroundColor = YZ_WhiteColor;
NSInteger count = items.count;
for (int i = 0; i < count; i++) {
UIButton *btn = [self buttonForToolBarWithTitle:items[i]];
btn.tag = 100 + i;
btn.layer.cornerRadius = 5;
[btn mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerY.equalTo(self);
make.height.mas_equalTo(btnHeight);
make.width.equalTo(???);
make.left.equalTo(???);
}];
}
}
return self;
}
我参考
Masonry
给出的Demo
得到了答案雷雷
将所有button的width都设为相等不就好了