問題記錄:在開發(fā)中,列表控件的UILabel的高度需要動態(tài)適應,這是需要根據實際的文字來計算label文字的寬高從而來實現(xiàn)cell的高低適應。
NSString *info = @"但是公司的高度是廣東省公司的廣東省高速度來開個大帥哥多撒謊個愛好就跟他說噶三公司噶是的剛好是我哥如果黑暗如果壞都干撒降低公司及嘎斯進歐冠賽歐結果就賽歐國際韶關;可垃圾費;阿爾加兩塊;三個身高薩嘎干撒的公司的高度上收到公司的公司都給ID搜狗破is打個屁偶是東莞IP手動皮革是滴哦蘋果是滴哦蘋果度搜皮為歐公司的漂漂是第三個是干撒噶是的噶雖然剛撒旦個撒公司的公司的高度";;
CGSize infoSize = CGSizeMake(tableView.frame.size.width, 1000);
NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:17.f ]};
//默認的
CGRect infoRect = [info boundingRectWithSize:infoSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil];
// 參數(shù)1: 自適應尺寸,提供一個寬度,去自適應高度
// 參數(shù)2:自適應設置 (以行為矩形區(qū)域自適應,以字體字形自適應)
// 參數(shù)3:文字屬性,通常這里面需要知道是字體大小
// 參數(shù)4:繪制文本上下文,做底層排版時使用,填nil即可
//上面方法在計算文字高度的時候可能得到的是帶小數(shù)的值,如果用來做視圖尺寸的適應的話,需要使用更大一點的整數(shù)值.取整的方法使用ceil函數(shù)
return height + ceil(infoRect.size.height);
鏈接:http://www.itdecent.cn/p/d7f7f01818f2
設置 UILabel 的 Frame 高度
在設置 UILabel 的 Frame 高度時,不能簡單的設置為字體的 font size。否則會將字體的一部分裁剪掉。因為 UILabel 在不同的字體設置下,對 Frame 的高度要求也不一樣,大多數(shù)情況下都比Font的高度設置要高一些。
一、sizeThatFits
使用 view 的 sizeThatFits 方法。
// return 'best' size to fit given size. does not actually resize view. Default is return existing view size
- (CGSize)sizeThatFits:(CGSize)size;
例子:
UILabel *testLabel = [[UILabel alloc] init];
testLabel.font = [UIFont systemFontOfSize:30];
testLabel.text = @"Today is a fine day";
CGSize size = [testLabel sizeThatFits:CGSizeMake(200, 30)];
NSLog(@"size = %@", NSStringFromCGSize(size));
輸出:size = {246.33333333333334, 36}
二、sizeToFit
使用 view 的 sizeToFit 方法。
注意:sizeToFit 會改變 view 原來的 bounds,而 sizeThatFits 不會。
// calls sizeThatFits: with current view bounds and changes bounds size.
- (void)sizeToFit;
例子
UILabel *testLabel = [[UILabel alloc] init];
testLabel.font = [UIFont systemFontOfSize:30];
testLabel.text = @"Today is a fine day";
[testLabel sizeToFit];
NSLog(@"size = %@", NSStringFromCGSize(testLabel.frame.size));
輸出:size = {246.33333333333334, 36}
三、sizeWithAttributes
使用 NSString 的 sizeWithAttributes 方法。
- (CGSize)sizeWithAttributes:(nullable NSDictionary<NSString *, id> *)attrs NS_AVAILABLE(10_0, 7_0);
例子
NSString *text = @"Today is a fine day";
UIFont *font = [UIFont systemFontOfSize:30];
CGSize size = [text sizeWithAttributes:@{
NSFontAttributeName : font
}];
NSLog(@"size = %@", NSStringFromCGSize(size));
輸出: size = {246.3134765625, 35.80078125}
四、boundingRectWithSize
使用 NSString 的 boundingRectWithSize 方法。
- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary<NSString *, id> *)attributes context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 7_0);