0

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
Pang
  • 9,564
  • 146
  • 81
  • 122
Chaorders
  • 123
  • 1
  • 6
  • Seems similar to: http://stackoverflow.com/questions/16848613/remove-one-action-from-multi-actions-in-target-action-uibutton – Pang Apr 13 '17 at 05:44
  • @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 Docs – Chaorders Apr 13 '17 at 05:58

1 Answers1

0

As per Apple Docs:

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

The Dreams Wind
  • 8,416
  • 2
  • 19
  • 49