首页 > 解决方案 > 为什么我不能从代码中自动调整 UILabel 的文本,但我可以通过 IB?

问题描述

场景:我只想在每个目标设备的 UILabel 中放置一个字符串。
也就是说,在一个 iPad 型号上,字符串被截断。另一方面不是。
我怀疑应用程序比 IB 更以代码为中心。
所以我希望能够以编程方式使用 UILabel。

这是代码:

class ViewController: UIViewController {
    @IBOutlet var myLabel: UILabel!

    @IBAction func addMessageAction(_ sender: UIBarButtonItem) {
        let msg = "Mother had a feeling, I might be too appealing. But I can understand."
        myLabel.text = msg
        myLabel.numberOfLines = 0
        myLabel.adjustsFontForContentSizeCategory = true
        myLabel.sizeToFit()

        myLabel.lineBreakMode = .byTruncatingTail
        myLabel.minimumScaleFactor = 0.5
    }

    @IBAction func exitAction(_ sender: UIBarButtonItem) {
        exit(0)
    }
}

这是我按下“消息”按钮后的屏幕: 在此处输入图像描述

这似乎只适用于我在 IB 中设置 UILabel 属性。

为什么它不能通过代码工作?

标签: iosswiftuilabelautoresize

解决方案


我试过你的代码,它工作得很好。是否有任何 Autolayout 约束不匹配?

你可以做一件事来改变字体大小以适应标签的宽度

myLabel.adjustsFontSizeToFitWidth = true

推荐阅读