使UILabel约束显示全宽

时间:2016-03-17 02:18:56

标签: ios swift uilabel nslayoutconstraint ios-autolayout

我努力实现让我的uilabel从左侧延伸到右侧(Full Width),我可以在故事板中轻松完成,但我在我的应用程序中有一部分需要显示uilabel progmatically。 这是我的代码:

textLabel.backgroundColor = UIColor.grayColor()
textLabel.text = StringsLabel.NOINTERNET
textLabel.textAlignment = .Center
textLabel.font = UIFont.boldSystemFontOfSize(24.0)
textLabel.translatesAutoresizingMaskIntoConstraints = false
centerView.addSubview(textLabel)

let centreXTopLabel:NSLayoutConstraint = NSLayoutConstraint(item: textLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: centerView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0);
        centerView.addConstraint(centreXTopLabel)

以下是我所拥有的截图:

enter image description here

2 个答案:

答案 0 :(得分:1)

将其固定在0点的视图的前导和尾随处:

let leading = NSLayoutConstraint(item: textLabel, attribute: .Leading, relatedBy: .Equal, toItem: centerView, attribute: .Leading, multiplier: 1, constant: 0)
let trailing = NSLayoutConstraint(item: textLabel, attribute: .Trailing, relatedBy: .Equal, toItem: centerView, attribute: .Trailing, multiplier: 1, constant: 0)
NSLayoutConstraint.activateConstraints([leading, trailing])

请注意,这会导致布局模糊 - 您需要添加一个垂直定位标签的约束。

答案 1 :(得分:0)

试试这个..

let views = ["textLabel" : textLabel]
let formatString = "|-[textLabel]-|"

 let constraints = NSLayoutConstraint.constraintsWithVisualFormat(formatString, options:.AlignAllTop , metrics: nil, views: views)

NSLayoutConstraint.activateConstraints(constraints)