- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary<NSString *, id> *)attributes context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 7_0);
// 參數(shù)1: 自適應(yīng)尺寸,提供一個(gè)寬度,去自適應(yīng)高度
// 參數(shù)2:自適應(yīng)設(shè)置 (以行為矩形區(qū)域自適應(yīng),以字體字形自適應(yīng))
// 參數(shù)3:文字屬性,通常這里面需要知道是字體大小
// 參數(shù)4:繪制文本上下文,做底層排版時(shí)使用,填nil即可
pragma mark -獲取文本寬度計(jì)算邏輯
#pragma mark -----計(jì)算文本寬度
-(CGFloat)getLabel:(NSString*)label withFontAttributeName:(UIFont*)font{
NSDictionary*attribute =@{NSFontAttributeName: font};
CGSize size = [label boundingRectWithSize:CGSizeMake(MAXFLOAT,0) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
return size.width+20;
}
獲取文本高度計(jì)算邏輯
- (CGSize)getLabel:(NSString*)label withFontAttributeName:(UIFont*)font{
NSDictionary*attribute =@{NSFontAttributeName: font};
CGSize size = [label boundingRectWithSize:CGSizeMake(kScreenWidth,500) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
return size;
}
//上面方法在計(jì)算文字高度的時(shí)候可能得到的是帶小數(shù)的值,如果用來(lái)做視圖尺寸的適應(yīng)的話,需要使用更大一點(diǎn)的整數(shù)值.取整的方法使用ceil函數(shù)
return height + ceil(infoRect.size.height);