码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2016-04-05 19:41:53      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

平时这些代码用的时候,总是要搜索查阅,自己索性整理下记一笔,节约生命。

实现是直接给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

 

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

标签:

原文地址:http://www.cnblogs.com/vokie/p/5356096.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!