0
votes

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
1
@Pang Thanks for reply, I think Aleksandr has solved this question. "If you specify a valid object in the target parameter, this method stops the delivery of the specified events to all action methods associated with that object." - Apple DocsChaorders

1 Answers

0
votes

As per Apple Docs:

the action parameter is not considered when stopping the delivery of events