Uilabel Sizetofit 방법이 제대로 작동하지 않습니다
-
22-12-2019 - |
문제
나는 한 줄에있는 UILABEL 안에 긴 텍스트를 보려고 노력하고 있습니다. UILabel은 UIScrollView의 하위 뷰이므로 전체 UILabel을 스크롤하고 볼 수 있습니다.
내 문제는 sizetofit 방법 만 부분적으로 작동하는 것입니다.
textLabel.attributedText = attributedString;
textLabel.numberOfLines = 1;
[textLabel sizeToFit];
textScrollView.contentSize = CGSizeMake(textLabel.frame.size.width, textLabel.frame.size.height);
.
UISCrollView 콘텐츠 크기는 uilable 전체를 보여주기에 충분하지만, 다음과 같은 선의 경우 :
그래서 나는 그 중 일부를 잠시 한 번씩 여기에서 나누려 노력할 것입니다. "
uilabel은 다음과 같습니다.
그래서 나는 som을 공유하려고 노력할 것입니다 ...
무엇을 잘못하고 있습니까?
해결책
코드가 켜지지 만 미세한 것은 아니지만 AutoLayout 사용이 확인되었습니다. 확인되지 않음 - 모든 것이 훌륭합니다 ...
다른 팁
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.