5

I want to make a string to fit the size of label. The code below doesn't change anything. What am I doing wrong?

nameLabel.font = UIFont.systemFont(ofSize: 30)
nameLabel.adjustsFontSizeToFitWidth = true
nameLabel.text = "fjggfjghggiuhgughuohgoihiohiohiughiugyiugyu8ftufuyguoy80houhuiy78rt6drtyreruti"
nameLabel.numberOfLines = 1
nameLabel.minimumScaleFactor = 0.5
shim
  • 9,289
  • 12
  • 69
  • 108
birdy
  • 943
  • 13
  • 25

1 Answers1

1

UIKit needs a hint about how many lines of text you want, or it doesn't know how much to scale down. If you want the whole text to fit into the label on one line, you also need: nameLabel.numberOfLines = 1.

Working playground example:

import Foundation
import UIKit

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
label.numberOfLines = 1
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
label.text = "Some very long text goes here"
Craig McMahon
  • 1,550
  • 1
  • 14
  • 36
  • thank you. I tried to add this line, but nothing changed – birdy Apr 24 '17 at 11:20
  • Your initial font size is quite large. Did you try a smaller minimum scale factor, like 0.1? Is the `nameLabel` in the code properly connected to the storyboard? – Craig McMahon Apr 24 '17 at 11:25
  • yes, I've tried. when set numerOfLines to 0 it works. But when string is short UIFont is smaller than 30. – birdy Apr 24 '17 at 11:40
  • It only works if initially set the font size to a really big value (say 100). And numberOfLines should be set to 0. – Roman Oct 05 '19 at 09:06
  • 1
    Note the default value for [`numberOfLines`](https://developer.apple.com/documentation/uikit/uilabel/1620539-numberoflines) is already `1`. – shim Jan 13 '21 at 15:43