NSArray *Arr = @[@"123456",@"123456789",@"qwertyuiop",@"asdfghjkl",@"zxcvbnm",@"abcdefg",@"aaaa",@"bbbb",@"cccc",@"f",@"fretretq",@"fewrtewt",@"a beautiful day",@"够了没有呢",@"哎 还是多写几个吧",@"丰富特权",@"123456",@"123456789",@"qwertyuiop",@"asdfghjkl",@"zxcvbnm",@"abcdefg",@"aaaa",@"bbbb",@"cccc",@"f",@"fretretq",@"fewrtewt",@"a beautiful day",@"够了没有呢",@"哎 还是多写几个吧",@"丰富特权"];
//创建各个Button
NSInteger currentRight = 0; // 记录当前Btn的right(右边)
NSInteger currentBotton = 0; // 记录当前btn的bottom(底部)
for (int i = 0; i < Arr.count; i++)
{
UIButton *Btn=[UIButton buttonWithType:UIButtonTypeCustom];
Btn.frame = CGRectMake(currentRight + 15, currentBotton + 30, 80, 25);
// 计算字体长度
CGSize size = [Arr[i] boundingRectWithSize:CGSizeMake(200, 30000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size;
// 更新btn的右边
currentRight = currentRight + size.width + 40;
// 判断是否换行
if (i < Arr.count - 1)
{
NSString *str = Arr[i + 1];
// 计算字体长度
CGSize size = [str boundingRectWithSize:CGSizeMake(200, 30000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size;
if (currentRight + size.width > SCREEN_WIDTH - 60)
{
currentRight = 0;
currentBotton = currentBotton + 45;
}
}
// 更新每个Btn的frame
CGRect frame = CGRectMake(Btn.frame.origin.x, Btn.frame.origin.y, size.width + 30, size.height +20);
Btn.frame = frame;
// 设置btn的属性
Btn.titleLabel.font=[UIFont systemFontOfSize:13];
Btn.backgroundColor=[UIColor clearColor];
[Btn setTitleColor:[UIColor colorWithRed:69/255.0 green:69/255.0 blue:68/255.0 alpha:1.0] forState:UIControlStateNormal];
[Btn setTitle:Arr[i] forState:UIControlStateNormal];
Btn.titleLabel.adjustsFontSizeToFitWidth = YES;
Btn.layer.cornerRadius=5;
Btn.layer.borderColor=[UIColor lightGrayColor].CGColor;
Btn.layer.borderWidth=0.7;
Btn.layer.masksToBounds=YES;
[self.view addSubview:Btn];
}