NSArray *Arr = @[@"123456",@"123456789",@"qwertyuiop",@"asdfghjkl",@"zxcvbnm",@"abcdefg",@"aaaa",@"bbbb",@"cccc",@"f",@"fretretq",@"fewrtewt",@"a beautiful day",@"夠了沒有呢",@"哎 還是多寫幾個吧",@"豐富特權(quán)",@"123456",@"123456789",@"qwertyuiop",@"asdfghjkl",@"zxcvbnm",@"abcdefg",@"aaaa",@"bbbb",@"cccc",@"f",@"fretretq",@"fewrtewt",@"a beautiful day",@"夠了沒有呢",@"哎 還是多寫幾個吧",@"豐富特權(quán)"];
//創(chuàng)建各個Button
NSInteger currentRight = 0; // 記錄當(dāng)前Btn的right(右邊)
NSInteger currentBotton = 0; // 記錄當(dāng)前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;
// 設(shè)置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];
}