【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;
        }
    }
}
發佈了91 篇原創文章 · 獲贊 58 · 訪問量 54萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章