UILabel不会在多行中显示



这是我的UILabel

let lblTitle: UILabel = {
let lbl=UILabel()
lbl.textColor=UIColor.darkGray
lbl.textAlignment = .center
lbl.font = UIFont.systemFont(ofSize: 36)
lbl.lineBreakMode = .byWordWrapping
lbl.numberOfLines=0
lbl.translatesAutoresizingMaskIntoConstraints=false
return lbl
}()

我添加了lineBreakMode并设置了应该启用多行的numberOfLines=0。我的视图是以编程方式添加的:

scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.addSubview(lblTitle)
lblTitle.text="Testing testing testing testing"
lblTitle.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive=true
lblTitle.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive=true
scrollView.addSubview(btnGetChoose)
btnGetChoose.heightAnchor.constraint(equalToConstant: 50).isActive=true
btnGetChoose.widthAnchor.constraint(equalToConstant: 150).isActive=true
btnGetChoose.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive=true
btnGetChoose.topAnchor.constraint(equalTo: lblTitle.bottomAnchor, constant: 10).isActive=true

为什么我的UILabel不会显示在多行中?

equal to替换为greater than or equal to

试试这个

lblTitle.heightAnchor.constraint(greaterThanOrEqualToConstant: 50).isActive=true

另请注意,应使用前导和尾随锚点(或宽度约束(为其超级视图(滚动视图(提供内容大小。

您必须设置宽度或前导和尾随以换行

lblTitle.widthAnchor.constraint(equalToConstant: self.view.frame.width / 2).isActive=true

按照 @keithbhunter 的建议,通过设置标签的前导/尾随锚点解决了这个问题

lblTitle.text="Testing testing testing testing"
lblTitle.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive=true
lblTitle.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive=true
lblTitle.leftAnchor.constraint(equalTo: scrollView.leftAnchor, constant: 12).isActive=true
lblTitle.rightAnchor.constraint(equalTo: scrollView.rightAnchor, constant: -12).isActive=true

相关内容

  • 没有找到相关文章

最新更新