【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

 

posted @ 2016-04-05 17:53  Mr轨迹  阅读(2551)  评论(0编辑  收藏  举报