UILabel sizeToFit method not working properly

后端 未结 6 980
梦如初夏
梦如初夏 2021-01-01 11:52

I\'m trying to show a long chunk of text inside a UILabel in one line. The UILabel is a subview of UIScrollView so I can scroll and see the entire UILabel.

My proble

相关标签:
6条回答
  • 2021-01-01 12:18

    Turns out the code is just fine - but the Use Autolayout was checked. Unchecked it - everything works just great...

    0 讨论(0)
  • 2021-01-01 12:21

    try

    textLabel.adjustsFontSizeToFitWidth  = YES;
    textLabel.minimumFontScale      =  0.5;  
    
    0 讨论(0)
  • 2021-01-01 12:24

    The most common reason for sizeToFit not working properly is the UILabel not having any autolayout constraints, for instance if you're implicitly relying on the view position remaining fixed relative to the top left. Adding any constraint at all (leading, top, centerY, anything) will fix it, presumably because it will result in layoutSubviews being called at some point, as suggested in Maxthon Chan's answer.

    0 讨论(0)
  • 2021-01-01 12:25

    Surprisingly, if you did not put a constraint on the label's width, this would work:

    [textLabel.superview layoutSubviews];
    

    I learned this by trial and error.

    0 讨论(0)
  • 2021-01-01 12:26

    Since you have restricted your Label to show only one line of Text and truncate the rest , it is behaving the same

    textLabel.attributedText = attributedString;
    textLabel.numberOfLines = 0;
    [textLabel sizeToFit];
    textLabel.lineBreakMode = NSLineBreakByWordWrapping;
    textScrollView.contentSize = CGSizeMake(textLabel.frame.size.width, textLabel.frame.size.height);
    

    Hope it will help you

    0 讨论(0)
  • 2021-01-01 12:38

    If you want to achieve this with auto layout turned on it's simple. Just make sure you add numberOfLines

    textLabel.adjustsFontSizeToFitWidth = YES;
    textLabel.numberOfLines = 0;
    
    0 讨论(0)
提交回复
热议问题