【发布时间】:2017-04-13 05:31:48
【问题描述】:
我已将多个目标添加到 UIButton。我想删除其中一个目标,但在 removeTarget:action:forControlEvents: 之后得到了 nil。
import UIKit
class IndexViewController: UIViewController {
lazy var sndBtn = UIButton(type: .system)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
view.addSubview(sndBtn)
sndBtn.setTitle("Hi", for: .normal)
sndBtn.addTarget(self, action: #selector(IndexViewController.onClick1(_:)), for: .touchUpInside)
sndBtn.addTarget(self, action: #selector(IndexViewController.onClick2(_:)), for: .touchUpInside)
print(sndBtn.actions(forTarget: self, forControlEvent: .touchUpInside) as Any)
sndBtn.removeTarget(self, action: #selector(IndexViewController.onClick1(_:)), for: .touchUpInside)
print(sndBtn.actions(forTarget: self, forControlEvent: .touchUpInside) as Any)
}
@objc
func onClick1(_ btn: UIButton) {
print("Method1")
}
@objc
func onClick2(_ btn: UIButton) {
print("Method2")
}
}
结果只是显示:
Optional(["onClick1:", "onClick2:"])
nil
【问题讨论】:
-
@Pang 感谢您的回复,我认为 Aleksandr 已经解决了这个问题。 “如果您在目标参数中指定了一个有效对象,此方法将停止将指定事件传递给与该对象关联的所有操作方法。” - 苹果文档