实现原理, 每一行用一个containerLineView来作为容器,如果换行,就从新生成一个containerLineView变量, containerLineView里面的每一个button用masonry来实现自动布局,很方便。
换行的判定: button的width + 间距(10) 是否大于屏幕宽度, 如果大于就换行。
示例:
UIView *containerLineView = [self getActivityContainerLineView:_activityView preView:nil];
UIButton *lastBtn;
UIButton *firstBtn;
// NSInteger lineCount = (NSInteger) (kUIScreenSize.width / 110);
CGFloat cWidth = 0;
for (int i = 0; i <= data.count; i++) {
ActivityButton *btn = [[ActivityButton alloc] init];
[btn addTarget:self action:@selector(clickActivityBtn:) forControlEvents:UIControlEventTouchUpInside];
//根据button的实际大小,来计算是否换行,原理就是计算button的长度如果超过屏幕的宽度就换行
CGSize size = [btn sizeThatFits:CGSizeMake(MAXFLOAT, 25)];
CGRect frame = btn.frame;
frame.size = size;
btn.frame = frame;
cWidth += size.width;
if (cWidth > kUIScreenSize.width - 20) { //超过屏幕宽度
containerLineView = [self getActivityContainerLineView:_activityView preView:containerLineView];
lastBtn = nil;
cWidth = size.width;
}
[containerLineView addSubview:btn];
cWidth += 10;
[btn mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(containerLineView);
make.height.equalTo(@25);
if (lastBtn) {
make.left.equalTo(lastBtn.mas_right).offset(10);
} else {
make.left.equalTo(containerLineView).offset(10);
}
}];
[self.activityButtons addObject:btn];
lastBtn = btn;
}
网友评论