思路:通过字符串算button的宽,for循环,如果多个button的宽相加大于屏幕宽,就换行,Y+=.以此类推
核心代码:
//通过字符串求宽或高,这里求的是宽,一搬咱们都是求高,总之.相求A就把A写成0或者MAXFLOAT,另外一个写具体的数.
//titleFont,他是字体,字号一定要和view上的字号一样,否则不准
//options:有四个选项:字符串的换行形式,有四个,根据情况来一搬是这俩
NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading
CGRect rect = [str boundingRectWithSize:CGSizeMake(MAXFLOAT, 25) options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : titleFont} context:nil];
我这里自定义了一个view
- (void)setTitleAry:(NSArray *)titleAry//存放字符串的数组
{
CGFloat pointX = 10.0;
CGFloat pointY = 10.0;
CGFloat allWidth = self.frame.size.width - 20;
UIFont *titleFont = [UIFont systemFontOfSize:15];
for (int i = 0; i < titleAry.count; i++) {
CGRect rect = [titleAry[i] boundingRectWithSize:CGSizeMake(MAXFLOAT, 25) options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : titleFont} context:nil];
CGFloat width = rect.size.width + 30;
if (pointX + width > allWidth) {//换行
pointX = 10;//X从新开始
pointY += 30;//换行后Y+
}
UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
but.frame = CGRectMake(pointX, pointY, width, 25);
// UIButton *but = [[UIButton alloc] initWithFrame:CGRectMake(pointX, pointY, width, 25)];
but.tag = i + 1000;
[but addTarget:self action:@selector(butAction:) forControlEvents:UIControlEventTouchUpInside];
but.layer.masksToBounds = YES;
but.layer.cornerRadius = 10;
[but setBackgroundImage:[UIImage imageWithColor:kHN_BackColor] forState:UIControlStateNormal];
[but setTitleColor:[UIColor blackColor ] forState:UIControlStateNormal];
[but setTitle:titleAry[i] forState:UIControlStateNormal];
but.titleLabel.font = titleFont;//一定要一样
pointX += (width + 5);//每次X都加上button宽和间距5
[self addSubview:but];
}
CGRect rect2 = self.frame;
rect2.size.height = pointY + 35;
self.frame = rect2;
}
网友评论