Uilabel SizetoFitメソッドが正しく機能していません
-
22-12-2019 - |
質問
Uilbel内の長いテキストを1行に表示しようとしています。 UilabelはUiscrollViewのサブビューですので、スクロールしてUilbel全体を表示できます。
私の問題は、SizetoFitメソッドのみが微妙な作品のみです。
textLabel.attributedText = attributedString;
textLabel.numberOfLines = 1;
[textLabel sizeToFit];
textScrollView.contentSize = CGSizeMake(textLabel.frame.size.width, textLabel.frame.size.height);
.
UISCrollViewコンテンツサイズは、UILABLE全体を表示するのに十分大きくなりますが、次のような行があります。
だから私はしばらく一度もここにいくつかを共有しようとします。 "
Uilabelは次のように表示されます。
だから私はSOMを共有しようとします...
私は何をしていますか?
解決
はコードを結ぶだけのものです - しかし使用オートレイアウトを使用しました。 それをチェックしない - すべてがすぐに動作します...
他のヒント
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;
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.
try
textLabel.adjustsFontSizeToFitWidth = YES;
textLabel.minimumFontScale = 0.5;
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
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.