UILabel不会以多行显示

时间:2018-05-09 14:52:28

标签: ios swift 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不会以多行显示?

3 个答案:

答案 0 :(得分:0)

equal to替换为greater than or equal to

试试这个

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

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

答案 1 :(得分:0)

通过设置@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

答案 2 :(得分:0)

你必须设置宽度或前导&尾随包裹

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