iOS获取Label高度

一、sizeThatFits

UILabel *testLabel = [[UILabel alloc] init];
testLabel.font = [UIFont systemFontOfSize:30];
testLabel.text = @"Today is a fine day";
CGSize size = [testLabel sizeThatFits:CGSizeMake(200, 30)];
NSLog(@"size = %@", NSStringFromCGSize(size));

输出结果 size = {246.33333333333334, 36}

二、sizeToFit

UILabel *testLabel = [[UILabel alloc] init];
testLabel.font = [UIFont systemFontOfSize:30];
testLabel.text = @"Today is a fine day";
[testLabel sizeToFit];
NSLog(@"size = %@", NSStringFromCGSize(testLabel.frame.size));

输出:size = {246.33333333333334, 36}
三、sizeWithAttributes

NSString *text = @"Today is a fine day";
UIFont *font = [UIFont systemFontOfSize:30];
CGSize size = [text sizeWithAttributes:@{
           NSFontAttributeName : font
           }];
NSLog(@"size = %@", NSStringFromCGSize(size)); 

输出: size = {246.3134765625, 35.80078125}
四、boundingRectWithSize

 
NSString *text = @"Today is a fine day";
UIFont *font = [UIFont systemFontOfSize:30];
CGRect suggestedRect = [text boundingRectWithSize:CGSizeMake(800, MAXFLOAT)
            options:NSStringDrawingUsesFontLeading
           attributes:@{ NSFontAttributeName : font }
            context:nil];
NSLog(@"size = %@", NSStringFromCGSize(suggestedRect.size));

输出: size = {200, 35.80078125}

四种方式对比
在设置字体为 30 的情况下,前两种使用 view 的方法返回 size = {246.33333333333334, 36} ,后两种使用 NSString 的方法返回 size = {246.3134765625, 35.80078125} 。使用 view 方法比使用 NSString 方法的返回的值略大。

我猜测其原因都是因为,文本渲染引擎在渲染一行文本的时候都需要在label的顶部和底部预留一小部分空间,应该是出于排版美观方面的考量。
在显示不同的 font size 的字体时,获得的字符串高度比 font size 大的值是不同的。
比如 font size 为 13 时,算出高度为 16,font size 为 20 时,算出高度为 24。

所以平常设置 UILabel 高度的时候,也不能简单的在 font height 基础之上加随意值。

https://www.jb51.net/article/98523.htm

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值