I have added multiple target to a UIButton. I'd like to remove one of these targets, but got nil after removeTarget:action:forControlEvents:.
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")
}
}
And the result just shows:
Optional(["onClick1:", "onClick2:"])
nil