根據(jù)文字內(nèi)容自適應(yīng)大小
NSArray * hotBtnArray = [NSArray arrayWithObjects:@"美食街",@"男裝",@"女裝",@"兒童玩具",@"娛樂秀",@"GAP",@"H&M",@"最新電影資訊", nil];
CGFloat w = 0;//保存前一個button的寬以及前一個button距離屏幕邊緣的距離
CGFloat y = 30;//用來控制button距離父視圖的高
for (int i = 0; i < hotBtnArray.count; i++) {
UIButton *button = [UIButton buttonWithTitle:hotBtnArray[i] titleColor:[UIColor whiteColor] font:[UIFont systemFontOfSize:12] target:self action:@selector(handleClick:)];
button.tag = 100 + i;
button.layer.cornerRadius = 5;
button.backgroundColor = HBRandomColor;
//根據(jù)計算文字的大小
NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
CGFloat length = [hotBtnArray[i] boundingRectWithSize:CGSizeMake(screenW - 20, 2000) options:NSStringDrawingUsesFontLeading attributes:attributes context:nil].size.width;
//設(shè)置lineBreakMode
button.titleLabel.lineBreakMode = NSLineBreakByClipping;
//設(shè)置button的frame,length+25防止文字被切掉
button.frame = CGRectMake(10 + w, y, length + 15 , 20);
//當(dāng)button的位置超出屏幕邊緣時換行 320 只是button所在父視圖的寬s度
if(10 + w + length + 15 > (screenW - 20)){
w = 0; //換行時將w置為0
y = y + button.frame.size.height + 10;//距離父視圖也變化
button.frame = CGRectMake(10 + w, y, length + 15, 20);//重設(shè)button的frame
}
w = button.frame.size.width + button.frame.origin.x;
[hotView addSubview:button];
}
特別注意文字大小的設(shè)置吭狡,不設(shè)置或者沖突都會導(dǎo)致自適應(yīng)大小會切掉部分文字