最后做成的效果就是上图
要实现上面这种效果图 有许多方法,例如for循环创建, for in 遍历,集合视图也可以,这里采用的是遍历方法。
写这个的主要问题有两个需要解决
第一个:是否超过父视图的右边界判断
第二个:超过边界换行展示
问题的解决都在代码里面了
CGFloat tagsTotalWidth = 0;
CGFloat tagsTotalHeigh = 0;
CGFloat tagHeight = 0;
for (NSString *str in tagArray) {
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(tagsTotalWidth, tagsTotalHeigh, 0, 0)];
label.font = [UIFont systemFontOfSize:12];
label.textAlignment = NSTextAlignmentCenter;
label.layer.cornerRadius = 2;
label.layer.borderWidth = 0.5;
label.layer.borderColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1].CGColor;
label.text = str;
label.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1];
[label sizeToFit];
label.frame = CGRectMake(tagsTotalWidth, tagsTotalHeigh, CGRectGetWidth(label.frame) + 4, CGRectGetHeight(label.frame)+2);
tagsTotalWidth += CGRectGetWidth(label.frame)+4;
tagHeight = CGRectGetHeight(label.frame);
if (tagsTotalWidth > self.frame.size.width) {
tagsTotalHeigh += CGRectGetHeight(label.frame) + 4;
tagsTotalWidth = 0;
label.frame = CGRectMake(tagsTotalWidth, tagsTotalHeigh, CGRectGetWidth(label.frame) + 4, CGRectGetHeight(label.frame));
tagsTotalWidth += CGRectGetWidth(label.frame)+4;
}
// CGFloat a = CGRectGetHeight(label.frame);
// NSLog(@"%f",a);
[self addSubview:label];
}
tagsTotalHeigh += tagHeight;
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, tagsTotalHeigh);
对于这一行代码
label.frame = CGRectMake(tagsTotalWidth, tagsTotalHeigh, CGRectGetWidth(label.frame) + 4, CGRectGetHeight(label.frame)+2);
里面的宽高分别+4,+2是为了label里面的字体不会和label的边界挨得太紧,可自行选择
附上小Demo:https://git.oschina.net/T1_mine/TagsView.git