您好我有以下代碼:添加約束到一個自定義的UIButton不起作用
class MyController {
override func viewDidLoad() {
self.addButtons()
super.viewDidLoad()
}
func addButtons() {
let cancelButton = UIButton(type: .custom)
let validateButton = UIButton(type: .custom)
cancelButton.setImage(UIImage(named: "cancel_icon"), for: .normal)
validateButton.setImage(UIImage(named: "validate_icon"), for: .normal)
cancelButton.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
validateButton.addTarget(self, action: #selector(validateAction), for: .touchUpInside)
cancelButton.translatesAutoresizingMaskIntoConstraints = false
validateButton.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(cancelButton)
self.view.addSubview(validateButton)
let leftCancel = NSLayoutConstraint(item: cancelButton, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 16)
let bottomCancel = NSLayoutConstraint(item: cancelButton, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: 20)
let widthCancel = NSLayoutConstraint(item: cancelButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 20)
let heightCancel = NSLayoutConstraint(item: cancelButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 20)
let rightValidate = NSLayoutConstraint(item: validateButton, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: 16)
let bottomValidate = NSLayoutConstraint(item: validateButton, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: 20)
let widthValidate = NSLayoutConstraint(item: validateButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 20)
let heightValidate = NSLayoutConstraint(item: validateButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 20)
NSLayoutConstraint.activate([leftCancel, bottomCancel, rightValidate, bottomValidate, widthCancel, heightCancel, widthValidate, heightValidate])
self.view.layoutIfNeeded()
}
func cancelAction() {
self.dismiss(animated: true, completion: nil)
}
func validateAction() {
self.dismiss(animated: true, completion: nil)
}
}
所以基本上我只是增加了寬度和高度約束兩個按鈕,我設置cancelButton
到左下和validateButton
右下。
我的按鈕沒有出現。當我按照這種方式設置按鈕的框架時,它的工作原理如下:
cancelButton.frame = CGRect(x: 16, y: self.view.frame.height - 40, width: 20, height: 20)
validateButton.frame = CGRect(x: self.view.frame.width - 36, y: self.view.frame.height - 40, width: 20, height: 20)
有人知道我的約束有什麼問題嗎? 謝謝!
我使用不同的語法,但從我所看到的,有兩件事。首先,20x20按鈕相當小。也許他們*被渲染 - 給他們一個backgroundColor來檢查。其次,兩個按鈕都呈現在相同的位置。但從我可以告訴你給他們足夠的自動佈局知道如何處理它們。 (除非* .notAnAttribute *不正確,我使用「anchor」語法樣式,從來沒有碰到這個。)編輯:Doh。我沒有看到一個按鈕正在領先,另一個按鈕正在領先。忘記我的第二個評論! – dfd
我相信你希望你的底部和尾部限制是負面的... – DonMag