以下代码位于UIView的子类中
我正在关闭中设置cancelButton
:
private var cancelButtonClosure: UIButton = {
...
button.addTarget(self, action: #selector(cancel(_:)), for: .touchUpInside)
...
}()
首先,我在函数内实例化了按钮,如下所示:
func showConfirmationView(...) {
...
let cancelButton = self.cancelButtonClosure
...
addSubview(cancelButton)
...
}
但是,这导致取消功能根本没有被调用(即使布局正确且按钮突出显示了)
所以我做了这些更改:
addTarget
中删除了cancelButtonClosure
addTarget
函数内添加了showConfirmationView
部分看起来像这样:
func showConfirmationView(...) {
...
let cancelButton = self.cancelButtonClosure
cancelButton.addTarget(self, action: #selector(cancel(_:)), for: .touchUpInside)
...
addSubview(cancelButton)
...
}
有效:调用了cancel
函数;但我不知道为什么。我真的很想知道为什么以前做过的没用。感谢您的见解!
答案 0 :(得分:0)
检查您的实施,因为这样的设置可以按预期工作:
private var cancelButton: UIButton = {
let btn = UIButton(type: .system)
btn.setTitle("Cancel", for: .normal)
btn.addTarget(self, action: #selector(cancelSomething(_:)), for: .touchUpInside)
return btn
}()
@objc func cancelSomething(_ sender: UIButton) {
print("Something has to be cancelled")
}
override func viewDidLoad() {
super.viewDidLoad()
showConfirmationView()
}
func showConfirmationView() {
cancelButton.sizeToFit()
cancelButton.center = view.center
view.addSubview(cancelButton)
}