longbow
longbow

Reputation: 1623

Swift: Are addTarget actions only allowing class methods?

I tried to add a target to a UIButton and stumbled upon a weird behaviour

if i try:

//h = a collection view header

switch myVar {

case "none":
    h.button.addTarget(self, action: "buttonTapped:", forControlEvents: .TouchUpInside)

    func buttonTapped(sender:AnyObject) {

    sendFriendRequest(self.targetUser,nil
    } 

}

I get SIGABRT - with "selector not found"

but if I move the function out of the switch case and make it a method of my ViewController, everything works as expected.

Anyone has an explanation for that? Is is just not allowed or are there technical reasons?

Upvotes: 1

Views: 2249

Answers (2)

fatihyildizhan
fatihyildizhan

Reputation: 8832

You can call any method in the project by using other class's instance instead of self.

Check this answer for the details. https://stackoverflow.com/a/33068386/2125010

Upvotes: 0

InkGolem
InkGolem

Reputation: 2762

Selectors don't need to be class functions, but they must visible to the object call the selector (i.e. can't be marked as private or inside a method).

Upvotes: 2

Related Questions