iOS 計(jì)算帶有行間距的字符串的高度

這個(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;

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容