CGFloat w = 0;
CGFloat h = 10;
for (int i = 0; i < self.zuiXingArray.count; i ++) {
//获取文字的长度
NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
CGFloat length = [self.zuiXingArray[i] boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
NSLog(@"%f",length);
UIButton *button = [[UIButton alloc]init];
button.titleLabel.font = [UIFont systemFontOfSize:15];
button.frame = CGRectMake(10 + w, h, length + 15 , 30);
//当大于屏幕的宽度自动换
if (10 + w + length + 15 > Width)
{
w = 0;
h = h + button.frame.size.height + 10;
button.frame = CGRectMake(10 + w, h, length + 15 , 30);
}
w = button.frame.size.width + button.frame.origin.x;
[button setTitle:self.zuiXingArray[i] forState:UIControlStateNormal];
button.backgroundColor = [UIColor redColor];
[self.MainVIew addSubview:button];
}
转载于:https://my.oschina.net/gongzhiming/blog/650667