我正在尝试添加一个按钮并以编程方式设置约束,但我不断收到此错误并且无法弄清楚我的代码出了什么问题。我在这里看过其他问题,但它们对我的情况没有太大帮助。
btn.setTitle("mybtn", for: .normal)
btn.setTitleColor(UIColor.blue, for: .normal)
btn.backgroundColor = UIColor.lightGray
view.addSubview(btn)
btn.translatesAutoresizingMaskIntoConstraints = false
let left = NSLayoutConstraint(item: btn, attribute: .leftMargin, relatedBy: .equal, toItem: view, attribute: .leftMargin, multiplier: 1.0, constant: 0)
let right = NSLayoutConstraint(item: btn, attribute: .rightMargin, relatedBy: .equal, toItem: view, attribute: .rightMargin, multiplier: 1.0, constant: 0)
let top = NSLayoutConstraint(item: btn, attribute: .top, relatedBy: .equal, toItem: topLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 0)
btn.addConstraints([left, right, top])
向视图添加约束时,"[约束中]涉及的任何视图必须是接收视图本身,或者是接收视图的子视图"。您正在将约束添加到btn
,因此它不了解约束引用的view
该怎么做,因为它既不是btn
也不是btn
的子视图。如果将约束添加到 view
而不是 btn
中,则会解决此错误。
或者更好的是,正如 Khalid 所说,改用activate
,在这种情况下,您无需担心在视图层次结构中的哪个位置添加约束:
let btn = UIButton(type: .system)
btn.setTitle("mybtn", for: .normal)
btn.setTitleColor(.blue, for: .normal)
btn.backgroundColor = .lightGray
view.addSubview(btn)
btn.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
btn.leftAnchor.constraint(equalTo: view.leftAnchor),
btn.rightAnchor.constraint(equalTo: view.rightAnchor),
btn.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor)
])
使用激活约束。 关闭iOS 9,您可以使用激活
btn.setTitle("mybtn", for: .normal)
btn.setTitleColor(UIColor.blue, for: .normal)
btn.backgroundColor = UIColor.gray
btn.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(btn)
let left = NSLayoutConstraint(item: btn, attribute: .leftMargin, relatedBy: .equal, toItem: view, attribute: .leftMargin, multiplier: 1.0, constant: 0)
let right = NSLayoutConstraint(item: btn, attribute: .rightMargin, relatedBy: .equal, toItem: view, attribute: .rightMargin, multiplier: 1.0, constant: 0)
let top = NSLayoutConstraint(item: btn, attribute: .top, relatedBy: .equal, toItem: topLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 0)
// here you have to call activate constraints everything will work
NSLayoutConstraint.activate([left, right, top])
示例项目
尝试向view
添加left
和right
约束,而不是btn
。