iosuilabel

UILabel: adjustsFontSizeToFitWidth doesn't work


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

Solution

  • 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"