我正在努力实现让我的 uilabel 从左侧拉伸(stretch)到右侧(全宽),我可以在 Storyboard中轻松完成,但我的应用程序中有一部分需要以编程方式显示 uilabel。 这是我的代码:
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)
这是我得到的截图:
最佳答案
在 0 点将其固定到 View 的前导和尾随:
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])
请注意,这将导致布局不明确——您需要添加一个垂直定位标签的约束。
关于ios - 使 UILabel 约束显示全宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36050518/