UILabel 正确获得height的方法

现在用的最多的方法是:
UILabel *label = [[UILabel alloc] initWithFrame:...];
label.text = NSLocalizedString(@"Some long text here...");
label.numberOfLines = 0;
CGSize maxSize = CGSizeMake(label.bounds.size.width, CGFLOAT_MAX);
CGSize textSize = [label.text sizeWithFont:label.font
constrainedToSize:maxSize];
label.frame = CGRectMake(10, 10, textSize.width, textSize.height);
而这是错误的。原因是:
如果未来label的可以配置其他行间距,自定义字体等等,那么此方法便会失效。
其实,ios已经UILabel可以支持不同的字体属性,比如大小,颜色。所以此方法已经不再是正确的了。
正确的方法应该是:
//UILabel height
CGSize maxSize = CGSizeMake(200.0f, CGFLOAT_MAX);
CGSize requiredSize = [label sizeThatFits:maxSize];
label.frame = CGRectMake(10, 10, size.width, size.height);
参考:
attributedText
The styled text displayed by the label.

@property(nonatomic,copy) NSAttributedString *attributedText
Discussion
This property is nil by default. Assigning a new value to this property also replaces the value of the text property with the same string data, albeit without any formatting information. In addition, assigning a new a value updates the values in the font, textColor, and other style-related properties so that they reflect the style information starting at location 0 in the attributed string.

Availability
Available in iOS 6.0 and later.
Declared In
UILabel.h
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值