【iOS界面开发】iOS下,UILabel自适应高度的方法

主要思路是通过调用UILabel- (CGSize)sizeThatFits:(CGSize)size方法来得到label的自适应高度值。

注意这里不能调用NSString- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode方法来获得高度,因为如果未来label的可以配置其他行间距,自定义字体等等,那么此方法便会失效。 其实,iOS的UILabel已经可以支持不同的字体属性,比如大小,颜色。所以此方法已经不再是正确的了

1.针对非AutoLayout的情况,直接调整frame:


- (void)autoHeightOfLabel:(UILabel *)label{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(label.frame.size.width, FLT_MAX);

    CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];

    //adjust the label the the new height.
    CGRect newFrame = label.frame;
    newFrame.size.height = expectedLabelSize.height;
    label.frame = newFrame;
    [label updateConstraintsIfNeeded];
}

2.针对AutoLayout的情况,需要更新约束:


- (void)autoHeightOfLabel:(UILabel *)label{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(label.frame.size.width, FLT_MAX);

    //add the new height constraint to the label
    for (NSLayoutConstraint *constraint in label.constraints) {
        if (constraint.firstItem == label && constraint.firstAttribute == NSLayoutAttributeHeight && constraint.secondItem == nil) {
            constraint.constant = expectedLabelSize.height;
            break;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值