【iOS】UILabel多行文本的高度計算


平時這些代碼用的時候,總是要搜索查閱,自己索性整理下記一筆,節約生命。

實現是直接給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                                                     NSStringDrawingUsesFontLeading
16                                          attributes:attribute
17                                             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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM