Johnathon Sullinger
Johnathon Sullinger

Reputation: 7414

Selector can't find instance method

I'm trying to register a method as an action for a UISwipeGestureRecognizer within my view controller. The target view is a custom view that I've built with a UIView subclass, as that's where I want the swipe targeted at. The problem I'm having is that I don't know how to set the action to be a method in the UIViewController. I can do that when I drag/drop the gesture to the View in interface builder, and then drag out an action to the controller.

func swiped(_ sender: UISwipeGestureRecognizer) {
}

func addGestureToView(_ view: CardView) {
    let gesture = UISwipeGestureRecognizer(target: view, action: Selector("swiped:"))
    gesture.direction = .up
    view.addGestureRecognizer(gesture)
}

I've also tried to use

let gesture = UISwipeGestureRecognizer(target: view, action: #selector(swiped(_:)))

Both of these approaches gives me the following exception of:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[testapp.CardView swiped:]: unrecognized selector sent to instance

I assume that is because it is looking for swiped: within the CardView target, and not the method that exists in the Controller. How can I specify that I want it to use the Controller for the action, while applying the gesture itself only to the CardView?

Upvotes: 1

Views: 361

Answers (1)

Irfan Anwar
Irfan Anwar

Reputation: 1918

change this line :

let gesture = UISwipeGestureRecognizer(target: view, action: Selector("swiped:"))

to:

let gesture = UISwipeGestureRecognizer(target: self, action: #selector(swiped(_:)))

Explanation

target: in UISwipeGestureRecognizer defines where your action method will be called, by defining self we are telling that our swipe gesture action should be called from UIViewcontroller not from CardView

action: in UISwipeGestureRecognizer defines the method that should be called on swipe gesture.

Upvotes: 1

Related Questions