1、首先先展示一下要實現(xiàn)的效果:
2哨鸭、如果整個頁面使用collectionView來布局就比較簡單了受扳,但是如果是tableview的cell上來實現(xiàn)這種效果的話,高度不是很好控制兔跌,我使用了tableview自動行高,然后再cell里賦值的時候進行masonry布局峡蟋,這里要控制好不要重復創(chuàng)建標簽坟桅,根據(jù)具體需求可以選擇傳入一次數(shù)據(jù)源,也可以每次創(chuàng)建標簽的時候蕊蝗,把之前創(chuàng)建的標簽刪除掉仅乓,tableviewcell中的代碼如下:
-(void)setTagArray:(NSArray *)tagArray{
_tagArray = tagArray;
NSArray *currentArray = tagArray;
NSInteger index = 0;
CGFloat width = 0;
CGFloat top = 15;
if (tagArray != nil) {
if (currentArray.count == 0) {
UIView *smallView = [UIView new];
[self.contentView addSubview:smallView];
[smallView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.top.bottom.equalTo(self.contentView);
make.height.mas_equalTo(0.1);
}];
}
}
for (NSDictionary *tagDic in currentArray) {
index ++;
CGRect rect = [tagDic[@"name"] boundingRectWithSize:CGSizeMake(MAXFLOAT, 25) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13]} context:nil];
UILabel *nameLabel = [[UILabel alloc]init];
nameLabel.text = SNHNoNilString(tagDic[@"name"]);
nameLabel.font = [UIFont systemFontOfSize:13];
nameLabel.textAlignment = NSTextAlignmentCenter;
nameLabel.layer.cornerRadius = 3;
nameLabel.layer.borderWidth = 0.5;
nameLabel.layer.borderColor = [UIColor snh_d5d6d7Color].CGColor;
[self.contentView addSubview:nameLabel];
if (index == 1) {
width = 15 + rect.size.width + 25 + 12;
}else{
width = width + rect.size.width + 25 + 12;
}
if ((width + 15) > snh_screenWidth()) {
top = top + 40;
}
if (_previousLabel == nil) {
[nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(self.contentView.mas_left).offset(15);
make.top.mas_equalTo(self.contentView.mas_top).offset(top);
if (index == _tagArray.count) {
make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(-15);
}
make.size.mas_equalTo(CGSizeMake(rect.size.width + 25, 25));
}];
}else{
[nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
NSLog(@"====%f",_previousLabel.frame.origin.x);
if ((width + 15) > snh_screenWidth()) {
make.left.mas_equalTo(self.contentView.mas_left).offset(15);
make.top.mas_equalTo(self.contentView.mas_top).offset(top);
if (index == _tagArray.count) {
make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(-15);
}
}else{
make.left.mas_equalTo(_previousLabel.mas_right).offset(12);
make.centerY.mas_equalTo(_previousLabel.mas_centerY);
if (index == _tagArray.count) {
make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(-15);
}
}
make.size.mas_equalTo(CGSizeMake(rect.size.width + 25, 25));
}];
}
if ((width + 15) > snh_screenWidth()) {
width = 15 + rect.size.width + 25 + 12;
}
_previousLabel = nameLabel;
}
}
以上是代碼,要注意最后一個標簽與cell底部有約束蓬戚,來實現(xiàn)自動行高