如何在Swift中使用多行文本居中UILabel?

时间:2017-11-09 08:38:13

标签: swift uilabel

我想以编程方式将带有多行文本的标签居中。我已将它添加到以下约束中,但它只显示在一行上!如何在不超出屏幕边界的情况下显示多行?

let noResults = UILabel()

noResults.text = self.emptyMessage
noResults.lineBreakMode = .byWordWrapping

noResults.minimumScaleFactor = 0.5
noResults.textAlignment = .center
noResults.font = UIFont(name: "Montserrat-Light", size: 20.0)!
noResults.numberOfLines = 0
noResults.adjustsFontSizeToFitWidth = true

noResults.sizeToFit()


noResults.textColor = UIColor.lightGray
noResults.translatesAutoresizingMaskIntoConstraints = false

self.view.addSubview(noResults)

let yConstraint = NSLayoutConstraint(item: noResults, attribute: .centerY, relatedBy: .equal, toItem: noResults.superview, attribute: .centerY, multiplier: 1, constant: -(self.navigationController?.navigationBar.frame.height)!)
let xConstraint = NSLayoutConstraint(item: noResults, attribute: .centerX, relatedBy: .equal, toItem: noResults.superview, attribute: .centerX, multiplier: 1, constant: 0)


NSLayoutConstraint.activate([yConstraint, xConstraint])

2 个答案:

答案 0 :(得分:2)

您只需要添加宽度约束。

答案 1 :(得分:0)

您可以使用Storyboard轻松完成,只需将宽度限制赋予 UILabel ,并在属性检查器中将属性设置为ZERO(0)。

snapShot