UILabel text not automatically resized using Auto Layout

微笑、不失礼 提交于 2019-11-30 12:35:07

You need

myLabel.adjustsFontSizeToFitWidth = YES;
myLabel.minimumScaleFactor = .5f;

Then the label font size will be auto adjusted.

Along with the setting of adjustsFontSizeToFitWidth and the minimumScaleFactor, you also need to set the content compression of the label to have a low priority. Check out the "Compression Resistance and Content Hugging" section of this objc.io essay. Basically, if your label has a lower compression resistance priority than the trailing constraint, the label should get resized:

[myLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow
                                 forAxis:UILayoutConstraintAxisHorizontal];

I solved this problem by setting a required width constraint to the view I was linking the label to.

   NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0f constant:width];

And make sure the priority for this constraint is set to UILayoutPriorityRequired.

[constraint setPriority:UILayoutPriorityRequired];

Text was resizing when pinning the label to the superview but not to the textfield, so I deduced there must be a problem with intrinsic sizes of elements involved in the layout calculation for the label's final width.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!