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

iOS 获取 UILabel 的宽度

时间:2018-11-15 18:33:14      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:use   uila   label   break   tor   ring   name   mutable   line   

 1 /**
 2  *  获取高度
 3  *
 4  *  @param font  目标字体
 5  *  @param width 约束宽度
 6  *
 7  *  @return 目标高度
 8  */
 9 - (CGFloat)ptv_heightWithFont:(UIFont *)font constrainedToWidth:(CGFloat)width {
10     UIFont *textFont = font ? font : [UIFont systemFontOfSize:[UIFont systemFontSize]];
11     
12     CGSize textSize;
13     
14 #if __IPHONE_OS_VERSION_MIN_REQUIRED < 70000
15     if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
16         NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
17         paragraph.lineBreakMode = NSLineBreakByWordWrapping;
18         NSDictionary *attributes = @{NSFontAttributeName: textFont,
19                                      NSParagraphStyleAttributeName: paragraph};
20         textSize = [self boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
21                                       options:(NSStringDrawingUsesLineFragmentOrigin |
22                                                NSStringDrawingTruncatesLastVisibleLine)
23                                    attributes:attributes
24                                       context:nil].size;
25     } else {
26         textSize = [self sizeWithFont:textFont
27                     constrainedToSize:CGSizeMake(width, CGFLOAT_MAX)
28                         lineBreakMode:NSLineBreakByWordWrapping];
29     }
30 #else
31     NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
32     paragraph.lineBreakMode = NSLineBreakByWordWrapping;
33     NSDictionary *attributes = @{NSFontAttributeName: textFont,
34                                  NSParagraphStyleAttributeName: paragraph};
35     textSize = [self boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
36                                   options:(NSStringDrawingUsesLineFragmentOrigin |
37                                            NSStringDrawingTruncatesLastVisibleLine)
38                                attributes:attributes
39                                   context:nil].size;
40 #endif
41     
42     return ceil(textSize.height);
43 }

 

iOS 获取 UILabel 的宽度

标签:use   uila   label   break   tor   ring   name   mutable   line   

原文地址:https://www.cnblogs.com/lz465350/p/9964871.html

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