UILabel sizeToFit method not working properly

2019-02-11 22:09发布

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 problem is that the sizeToFit method only partialy works.

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

The UIScrollView content size gets big enough to show the entire UILable, but for a line like:

so i'll try to share some of them here every once in a while."

The UILabel shows:

so i'll try to share som...

What am I doing wrong?

7条回答
霸刀☆藐视天下
2楼-- · 2019-02-11 22:42

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.

查看更多
女痞
3楼-- · 2019-02-11 22:50

try

textLabel.adjustsFontSizeToFitWidth  = YES;
textLabel.minimumFontScale      =  0.5;  
查看更多
Bombasti
5楼-- · 2019-02-11 22:57

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

查看更多
祖国的老花朵
6楼-- · 2019-02-11 23:05

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

查看更多
我想做一个坏孩纸
7楼-- · 2019-02-11 23:05

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.

查看更多
登录 后发表回答