多行文本不适合 UILabel
Posted
技术标签:
【中文标题】多行文本不适合 UILabel【英文标题】:Multiline text not fitting into UILabel 【发布时间】:2021-03-03 17:28:19 【问题描述】:我有这个代码:
class ViewController: UIViewController
private var nameLabel = UILabel()
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view.
updateLable()
func updateLable ()
nameLabel = UILabel(frame: view.frame)
nameLabel.text = "Michael Dell Arron Henry Mitchell duve soooooooooooooooooooooooooc"
nameLabel.backgroundColor = .green
nameLabel.numberOfLines = 0
nameLabel.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(nameLabel)
NSLayoutConstraint.activate([
nameLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor , constant: 0),
nameLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor , constant: 0)
])
nameLabel.isHidden = false
我无法将文本放入标签中。我用 numberOfLines = 0
和 sizeToFit()
检查了其他 cmets,但这似乎不起作用。
这是目前的样子:
【问题讨论】:
【参考方案1】:您需要限制标签的宽度才能使其换行。您可以:
1。设置宽度约束
NSLayoutConstraint.activate([
nameLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor , constant: 0),
nameLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor , constant: 0),
nameLabel.widthAnchor.constraint(equalToConstant: 100) /// here!
])
结果:
2。为父视图设置前导和尾随约束
NSLayoutConstraint.activate([
nameLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor , constant: 0), /// you can delete this
nameLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor , constant: 0),
/// here!
nameLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
nameLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor)
])
结果:
【讨论】:
以上是关于多行文本不适合 UILabel的主要内容,如果未能解决你的问题,请参考以下文章