嗨,谢谢你。我试图将两个UIButtons绑定到UIViewController
view
,如下所示:
首先声明它们:
fileprivate var deleteButton: UIButton = UIButton(type: .system)
fileprivate var addButton: UIButton = UIButton(type: .system)
接下来的设置:
private func setupButtons() {
deleteButton.setTitle("Delete", for: .normal)
addButton.setTitle("Add", for: .normal)
deleteButton.sizeToFit()
addButton.sizeToFit()
deleteButton.alpha = 1
addButton.alpha = 1
view.addSubview(deleteButton)
view.addSubview(addButton)
view.addConstraint(NSLayoutConstraint(item: deleteButton,
attribute: .leading,
relatedBy: .equal,
toItem: view,
attribute: .leading,
multiplier: 1.0,
constant: 0))
view.addConstraint(NSLayoutConstraint(item: deleteButton,
attribute: .bottom,
relatedBy: .equal,
toItem: view,
attribute: .bottom,
multiplier: 1.0,
constant: 0))
view.addConstraint(NSLayoutConstraint(item: addButton,
attribute: .trailing,
relatedBy: .equal,
toItem: view,
attribute: .trailing,
multiplier: 1.0,
constant: 0))
view.addConstraint(NSLayoutConstraint(item: addButton,
attribute: .bottom,
relatedBy: .equal,
toItem: view,
attribute: .bottom,
multiplier: 1.0,
constant: 0))
}
但是运行模拟器会将左侧的两个UIButton粘贴在一起,默认的CGRect帧分配给它们。
你可能知道我做错了什么?我觉得我很接近,但也许它与重新绘制视图有关?
答案 0 :(得分:1)
您应该将translatesAutoresizingMaskIntoConstraints
设置为false
// before activate constraint
deleteButton.translatesAutoresizingMaskIntoConstraints = false
addButton.translatesAutoresizingMaskIntoConstraints = false
此外,您必须设置isActive = true,而不是使用addConstraint方法