简体   繁体   中英

Label does not adjust Font Size to fit width

在此处输入图片说明

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
}

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.

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: 在此处输入图片说明

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.

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