這個(gè)是計(jì)算普通字符串的....NSString的!
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode NS_DEPRECATED_IOS(2_0, 7_0, "Use -boundingRectWithSize:options:attributes:context:"); // NSTextAlignment is not needed to determine size
而帶有行間距的字符串是NSAttributedString, 屬性字符串,比NSString 多出了很多屬性
- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context NS_AVAILABLE_IOS(7_0);
這樣 就不用計(jì)算別的其他東西了...
補(bǔ)充,自己閑著沒事,就封裝了一個(gè)方法...歡迎大家使用:
#pragma mark - 計(jì)算cell高度? str 字符串長(zhǎng)度 typefaceName字體內(nèi)容 typefaceSize字體大小 scopeWidth顯示范圍的寬? scopeHeight顯示范圍的高
- (NSInteger )HeightStr:(NSString *)str typefaceName:(NSString *)typefaceName typefaceSize:(NSInteger)typefaceSize scopeWidth:(NSInteger)scopeWidth scopeHeight:(NSInteger)scopeHeight
{
NSDictionary * dic = [NSDictionary dictionary];
//1.獲得要顯示的文本 str
NSString * CellStr = str;
//計(jì)算高度
if (typefaceName == nil) {
dic = @{NSFontAttributeName:[UIFont systemFontOfSize:typefaceSize]};
}else{
//字體類型 大小
dic = @{NSFontAttributeName:[UIFont fontWithName:typefaceName size:typefaceSize]};
}
//字符串的顯示范圍
CGSize scope = CGSizeMake(scopeWidth, scopeHeight);
CGRect rect = [CellStr boundingRectWithSize:scope options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
int cellH = rect.size.height + 20;
return cellH;
}