How to use UIButton.addTarget in Swift 3

Specificlly, how to add selector in AddTarget()

I tried the following but non of them work


selectionButton.addTarget(self, action: Selector.init("selected:"), for: .touchUpInside)

selectionButton.addTarget(self, action: #selector(SingleQuestionViewController.selected(_:)), forControlEvents: .TouchUpInside)

Depends on many things you are hiding.


But first of all, you need check the exact method header in Swift:

func addTarget(AnyObject?, action: Selector, for: UIControlEvents)


And second, you need to check how you declared your `selected` method.

If you have written your `selected` method like this:

    func selected(sender: AnyObject) {
        //...
    }

Then the selector notation to this method needs to be like `#selector(SingleQuestionViewController.selected(sender:))`.


If your want to designate your method with `#selector(SingleQuestionViewController.selected(_:))`, you need to write the method as:

    func selected(_: AnyObject) {
        //...
    }


And if your View Controller has only one `selected(...)` method, and you use `#selector(..)` notation within the class,

you just need to write `#selector(selected)` to represent the method.


So, if you want to write a code very similar to the one that Swift Migrator would generate, you need to declare your `selected` method as:

    func selected(_ sender: AnyObject) {
        //...
    }

and use `addTarget` in this way:

        selectionButton.addTarget(self, action: #selector(SingleQuestionViewController.selected(_:)), for: .touchUpInside)


Write a Swift 2.2 code in Xcode 7 and make Xcode 8 migrate it, and you can learn many things.

How to use UIButton.addTarget in Swift 3
 
 
Q