NSArray * hotBtnArray = [NSArray arrayWithObjects:@"美食街",@"男装",@"女装",@"儿童玩具",@"娱乐秀",@"GAP",@"H&M",@"最新电影资讯", nil];
CGFloat w = 0;//保存前一个button的宽以及前一个button距离屏幕边缘的距离
CGFloat y = 30;//用来控制button距离父视图的高
for (int i = 0; i < hotBtnArray.count; i++) {
UIButton *button = [UIButton buttonWithTitle:hotBtnArray[i] titleColor:[UIColor whiteColor] font:[UIFont systemFontOfSize:12] target:self action:@selector(handleClick:)];
button.tag = 100 + i;
button.layer.cornerRadius = 5;
button.backgroundColor = HBRandomColor;
//根据计算文字的大小
NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
CGFloat length = [hotBtnArray[i] boundingRectWithSize:CGSizeMake(screenW - 20, 2000) options:NSStringDrawingUsesFontLeading attributes:attributes context:nil].size.width;
//设置lineBreakMode
button.titleLabel.lineBreakMode = NSLineBreakByClipping;
//设置button的frame,length+25防止文字被切掉
button.frame = CGRectMake(10 + w, y, length + 15 , 20);
//当button的位置超出屏幕边缘时换行 320 只是button所在父视图的宽s度
if(10 + w + length + 15 > (screenW - 20)){
w = 0; //换行时将w置为0
y = y + button.frame.size.height + 10;//距离父视图也变化
button.frame = CGRectMake(10 + w, y, length + 15, 20);//重设button的frame
}
w = button.frame.size.width + button.frame.origin.x;
[hotView addSubview:button];
}
特别注意文字大小的设置,不设置或者冲突都会导致自适应大小会切掉部分文字