我在 View Controller 上使用 IB 添加了一个 UIView
。我们称它为 redView
。
然后我在代码中使用自动布局约束固定了它的所有四个边,当我运行它时,它看起来像预期的那样。
现在我想以编程方式向此 View 添加一个 UILabel
并使用自动布局约束将其定位在中心。
下面是我到目前为止的代码。
import UIKit
class ViewController: UIViewController {
@IBOutlet private var redView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
redView.setTranslatesAutoresizingMaskIntoConstraints(false)
let leadingConstraint = NSLayoutConstraint(item: redView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 0)
let trailingConstraint = NSLayoutConstraint(item: redView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: 0)
let topConstraint = NSLayoutConstraint(item: redView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: redView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0)
view.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])
let label = UILabel()
label.text = "Auto Layout Exercise"
redView.addSubview(label)
let xCenterConstraint = NSLayoutConstraint(item: label, attribute: .CenterX, relatedBy: .Equal, toItem: redView, attribute: .CenterX, multiplier: 1, constant: 0)
let yCenterConstraint = NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: redView, attribute: .CenterY, multiplier: 1, constant: 0)
let leadingConstraint1 = NSLayoutConstraint(item: label, attribute: .Leading, relatedBy: .Equal, toItem: redView, attribute: .Leading, multiplier: 1, constant: 20)
let trailingConstraint1 = NSLayoutConstraint(item: label, attribute: .Trailing, relatedBy: .Equal, toItem: redView, attribute: .Trailing, multiplier: 1, constant: -20)
redView.addConstraints([xCenterConstraint, yCenterConstraint, leadingConstraint1, trailingConstraint1])
}
}
问题是标签没有出现在 redView
上。谁能告诉我这里缺少什么?
谢谢。
最佳答案
我很确定你还需要设置:
label.setTranslatesAutoresizingMaskIntoConstraints(false)
否则我认为约束不会应用于标签。
关于ios - 添加 subview 并以编程方式使用约束定位它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26721920/