思路:通過(guò)字符串算button的寬,for循環(huán),如果多個(gè)button的寬相加大于屏幕寬,就換行,Y+=.以此類推
核心代碼:
//通過(guò)字符串求寬或高,這里求的是寬,一搬咱們都是求高,總之.相求A就把A寫(xiě)成0或者M(jìn)AXFLOAT,另外一個(gè)寫(xiě)具體的數(shù).
//titleFont,他是字體,字號(hào)一定要和view上的字號(hào)一樣,否則不準(zhǔn)
//options:有四個(gè)選項(xiàng):字符串的換行形式,有四個(gè),根據(jù)情況來(lái)一搬是這倆
NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading
CGRect rect = [str boundingRectWithSize:CGSizeMake(MAXFLOAT, 25) options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : titleFont} context:nil];
我這里自定義了一個(gè)view
- (void)setTitleAry:(NSArray *)titleAry//存放字符串的數(shù)組
{
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從新開(kāi)始
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;
}