ios - 为什么我不能从代码中自动调整 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 属性。
为什么它不能通过代码工作?
解决方案
我试过你的代码,它工作得很好。是否有任何 Autolayout 约束不匹配?
你可以做一件事来改变字体大小以适应标签的宽度
myLabel.adjustsFontSizeToFitWidth = true
推荐阅读
- java - 弹性搜索 XContent Provider
- c++ - 如何从c ++中的字符串中获取所有十进制数
- excel - 为什么使用 Vlookup 时出现运行时错误 1004?
- java - 从自定义java数组列表中过滤最小值
- c++11 - Gmock - 严格的模拟和独特的 ptr - 如何将模拟传递给 impl
- android-studio - 如何将文件放入 Android/Data/com.mycomp.myapp?
- vue.js - 从 vuex 检索数据表的状态时,不更新分页
- c# - Publish build artifact through build.cake instead of Azure Devops
- verilog - 你如何在verilog中或一个带有单个位的向量?
- javascript - 快递中间件未登录到控制台