当前位置: 代码迷 >> 综合 >> Masonry 布局不等宽的标签并自动换行
  详细解决方案

Masonry 布局不等宽的标签并自动换行

热度:121   发布时间:2023-09-13 20:02:53.0

效果

Masonry 布局不等宽的标签并自动换行
image.png

demo

NSArray *array = @[@"一",@"二二",@"三三三",@"四四四四",@"五五五五五",@"一",@"二二",@"三三三",@"四四四四",@"五五五五五",@"一",@"二二",@"三三三",@"四四四四",@"五五五五五",@"一",@"二二",@"三三三",@"四四四四",@"五五五五五"];UIButton *listButton;__block float buttonRight;for (int i = 0; i < array.count; i++) {NSString *title = array[i];CGFloat titleW = [title sizeWithFont:Font(14) maxSize:CGSizeMake(MAXFLOAT, MAXFLOAT)].width + 20;UIButton *button = [UIButton new];button.backgroundColor = WHColor_1779ff;[button setTitle:title forState:UIControlStateNormal];[button setTitleColor:WhiteColor forState:UIControlStateNormal];button.titleLabel.font = Font(14);button.layer.cornerRadius = 10;button.layer.masksToBounds = YES;[self addSubview:button];[button mas_makeConstraints:^(MASConstraintMaker *make) {if (listButton) {buttonRight = buttonRight + 15 + titleW;if (buttonRight > SCREEN_WIDTH) {//下一排的第一个make.top.mas_equalTo(listButton.mas_bottom).offset(15);make.left.mas_equalTo(self.tagImageView).offset(0);buttonRight = 30 + titleW;}else{//非第一个make.top.mas_equalTo(listButton.mas_top).offset(0);make.left.mas_equalTo(listButton.mas_right).offset(15);}}else{//第一个make.top.mas_equalTo(tagView.mas_bottom).offset(25);make.left.mas_equalTo(self.tagImageView).offset(0);buttonRight = 30 + titleW;}make.size.mas_equalTo(CGSizeMake(titleW, 20));}];listButton = button;}