我试图通过编程方式添加按钮并设置约束,但我一直收到这个错误,并且无法弄清楚我的代码有什么问题。我已经查看了其他问题,但在我的情况下它们没有提供太多帮助。
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])