1

How do we increase the font size of label to match the height of the label?

In Swift 4 or Storyboard for Xcode 9, either programmatically or via interface builder.

I have attempted the following, which has been claimed to work by a few in Swift 3. - SO Q&A

label.minimumScaleFactor = 0.1
label.adjustsFontSizeToFitWidth = true
label.lineBreakMode = .byClipping
label.numberOfLines = 0

For testing purposes, I created a label that is the width of the screen and the height of the screen, yet the font size remains the default size. I also made the settings in the interface builder match that of the code above, with equally unsuccessful results.

McGuile
  • 818
  • 1
  • 11
  • 29
  • If you're attempting to scale _up_ the font, the system will not do that for you. The Q&A you're linking to gives an example of _calculating_ the scale-up ( https://stackoverflow.com/a/17622215/6875565), but you have to implement it. – particleman Aug 05 '18 at 01:24
  • set your label font size to maximum. not sure what is max but try like 1000. then use `label.minimumScaleFactor = 0.1` and `label.adjustsFontSizeToFitWidth = true` to make is scale down – RJE Aug 05 '18 at 04:05
  • @RJE A couple of tests show that if the max font set is too large, the text is cropped by label height. This isn't acceptable. The method I've answered seems to work in all cases and the size is scaled proportional to the label height. – McGuile Aug 06 '18 at 04:24
  • @McGuile yes, that looks fine, your solution works but you don't have to have a fixed height if you put that in `viewDidLayoutSubviews` method or after(`testLabel.frame.height` will not be correct before that), any way I think the issue with `adjustsFontSizeToFitWidth` is probably with baselineAdjustment. `testLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters` may work(can set from storyboard too). so you don't have to do the calculation. – RJE Aug 07 '18 at 06:39

3 Answers3

3

Answering my own question. Answer found buried in the post I linked above.

If your UILabel has a fixed height, whether it be by points or by a multiplier of a superview, the font size can be set to any fraction of that height with one line of code:

testLabel.font = testLabel.font.withSize(testLabel.frame.height * 2/3)

where 2/3 is the height fraction of the label the text occupies.

McGuile
  • 818
  • 1
  • 11
  • 29
0

Have a simply solution for this. We can increase size default of label to 100 and set property min font size of the label ~ 1. I dont remember exactly this property. Im on mobile

Dong Nguyen
  • 93
  • 10
0

Set the label on the storyboard and just set font size to maximum and set property min font size of the label in property inspector then according to screwn size it will be adjustable.

Anil Kumar
  • 1,830
  • 15
  • 24