这是自己没事写的小demo,实现标签根据标签的文字长度进行流式布局。
效果如下
10行代码即可实现,简单易懂,废话不说,上代码
NSArray *btnTitles = @[@"华润苏果",@"乐城",@"柏兆记",@"银泰城",@"万达游乐园",@"皇冠假日酒店",@"霍山大酒店",@"之心城",@"西湖国际购物广场",@"苏果超市",@"锦江之星",@"万达广场",@"华润五彩城",@"大唐购物广场",@"三孝口",@"合肥南站",@"威斯汀酒店"];
NSInteger count = [btnTitles count];
NSLog(@"%ld",count);
CGFloat maxX = 15;
CGFloat row = 0;
CGFloat maxY = NavigationBarHeight+60;
for (int i=0; i<count;i++)
{
UILabel *lab = [[UILabel alloc]init];
lab.text = btnTitles[i];
lab.backgroundColor = [UIColor whiteColor];
lab.textColor = [UIColor grayColor];
lab.layer.cornerRadius = 5.0f;
lab.layer.masksToBounds = YES;
lab.font = [UIFont systemFontOfSize:14];
lab.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:lab];
NSString *str = btnTitles[i];
CGFloat width = (str.length+2)*15;
CGFloat height = 30;
if (maxX +width< Screen_Width) {
lab.frame = CGRectMake(maxX,maxY,width,height);
maxX = CGRectGetMaxX(lab.frame)+10;
}
else
{
row ++;
maxY += 45;
maxX = 15;
lab.frame = CGRectMake(maxX,maxY,width,height);
maxX = CGRectGetMaxX(lab.frame)+10;
}
}
代码就是这样了,是不是很简单?