1、首先先展示一下要实现的效果:
2、如果整个页面使用collectionView来布局就比较简单了,但是如果是tableview的cell上来实现这种效果的话,高度不是很好控制,我使用了tableview自动行高,然后再cell里赋值的时候进行masonry布局,这里要控制好不要重复创建标签,根据具体需求可以选择传入一次数据源,也可以每次创建标签的时候,把之前创建的标签删除掉,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底部有约束,来实现自动行高