简体   繁体   中英

Scaling font size to width of label iOS Swift

So, I recently starting learning Swift and was wondering how you would scale text within your labels depending on the screen size. I've seen a few questions similar to this, but they seem rather complicated. I'm trying to do it like this, but this doesn't seem to work.

UIlabel1.adjustsFontSizeToFitWidth = true

I've connected the label to the code and set a few constraints. Equal width Constraint Equal height Constraint Center X Alignment Constraint Vertical Space Constraint

The constraints are linked to the view controller so that the actual label size scales with the screen size. Any ideas?

You can use Autoshrink in storyboard

在此输入图像描述

Change it to Minimum Font Scale or Minimum Font Size

From the documentation for adjustsFontSizeToFitWidth :

Normally, the label text is drawn with the font you specify in the font property. If this property is set to true , and the text in the text property exceeds the label's bounding rectangle, the label reduces the font size until the string fits or the minimum font scale is reached. The default value for this property is false . If you change it to true , be sure that you also set an appropriate minimum font scale by modifying the minimumScaleFactor property.

This says that you must set minimumScaleFactor when using adjustsFontSizeToWidth in order for your font to be scaled.

But notice this scaling is one direction only. Your font size will get smaller if needed to display your text, but not larger than the font size you've set.

Given that, try setting the font size to the value appropriate for the largest screen on which your app will run. On smaller screens, it will scale down to fit, as far as the limit you specify for minimumScaleFactor will allow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM