標籤:
平時這些代碼用的時候,總是要搜尋查閱,自己索性整理下記一筆,節約生命。
實現是直接給NSString類添加一個分類,並添加了計算文本高度的兩個方法:
聲明代碼:
1 #import <Foundation/Foundation.h> 2 3 @interface NSString (Size) 4 5 /** 6 * 計算單行文本的高度 7 */ 8 - (CGFloat)heightWithLabelFont:(UIFont *)font; 9 /**10 * 計算多行文本的高度11 */12 - (CGFloat)heightWithLabelFont:(UIFont *)font withLabelWidth:(CGFloat)width;13 @end
具體的實現代碼:
1 #import "NSString+Size.h" 2 3 @implementation NSString (Size) 4 5 - (CGFloat)heightWithLabelFont:(UIFont *)font withLabelWidth:(CGFloat)width { 6 CGFloat height = 0; 7 8 if (self.length == 0) { 9 height = 0;10 } else {11 NSDictionary *attribute = @{NSFontAttributeName:font};12 CGSize rectSize = [self boundingRectWithSize:CGSizeMake(width, MAXFLOAT)13 options:NSStringDrawingTruncatesLastVisibleLine|14 NSStringDrawingUsesLineFragmentOrigin|15 NSStringDrawingUsesFontLeading16 attributes:attribute17 context:nil].size;18 height = rectSize.height;19 }20 return height;21 }22 23 - (CGFloat)heightWithLabelFont:(UIFont *)font {24 CGFloat height = 0;25 if (self.length == 0) {26 height = 0;27 }else{28 CGSize rectSize = [self sizeWithAttributes:@{NSFontAttributeName:font}];29 height = rectSize.height;30 }31 return height;32 }33 34 @end
【iOS】UILabel多行文本的高度計算