l30c0d35
l30c0d35

Reputation: 807

Label does not adjust Font Size to fit width

enter image description here

This is how my app looks although I entered this code inside my ViewController class:

@IBOutlet var label: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    label.text = "Hello World"
    label.adjustsFontSizeToFitWidth = true
    label.numberOfLines = 1
    label.minimumScaleFactor = 0.1
}

Upvotes: 2

Views: 1602

Answers (3)

Austin Marino
Austin Marino

Reputation: 144

I was able to get my UILabel font to dynamically adjust to the necessary size to fit into its parent by following this simple gitconnected article (See link to get all required code!!). I only needed to make two adjustments which were adding the lines label.baselineAdjustment = .alignCenters and label.numberOfLines = 1 so that my label creation now looked like this...

let dynamicFontLabel: UILabel = {
    let label = UILabel()
    label.font = .systemFont(ofSize: 40)
    label.textAlignment = .center
    label.numberOfLines = 1;
    label.textColor = .black
    label.adjustsFontSizeToFitWidth = true
    label.baselineAdjustment = .alignCenters
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

The label.baselineAdjustment = .alignCenters property ensured that if my font size was too large and needed to be downsized, my text would still remain centered vertically in the UILabel. I also only wanted my text to only span one line so if you want more than that you can just remove the label.numberOfLines = 1 property.

Upvotes: 0

Jogendar Choudhary
Jogendar Choudhary

Reputation: 3494

Your text data is not more than label width that's why label text font is same as already set. IF your text data is more then label width then it will adjust font according to the width.

Please check with label text: "This is the demo to test label text is adjustable or not. You need to test it with this demo data"

Your label font will adjust according to the width.

Upvotes: 1

Raghav Grandhi
Raghav Grandhi

Reputation: 66

The font will adjust if the given text is greater than the width of the label.

Try this in playground:

//: A UIKit based Playground for presenting user interface

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
 override func loadView() {
    let view = UIView()
    view.backgroundColor = .white

    let label = UILabel()
    label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)

    label.adjustsFontSizeToFitWidth = true
    label.numberOfLines = 1
    label.backgroundColor =  UIColor.lightGray

    label.text = "Hello World! How are you doing today? "
    label.textColor = .black

    view.addSubview(label)
    self.view = view
 }
}
 // Present the view controller in the Live View window
 PlaygroundPage.current.liveView = MyViewController()

The result is the following: enter image description here

Upvotes: 0

Related Questions