iOS 获取 UILabel 的宽度

 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 }

 

转载于:https://www.cnblogs.com/lz465350/p/9964871.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值