Leah Zorychta
Leah Zorychta

Reputation: 13419

Can't get UISwipeGestureRecognizer to work

I'm making a sidebar on my app so that when you swipe right it opens, I am using this code in the object I made called sidebar:

_swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self.superview action:@selector(swiped)];

[_swipeRecognizer setDirection: UISwipeGestureRecognizerDirectionRight];

[self.superview addGestureRecognizer:_swipeRecognizer];

And this of course crashes and throws the error:

[UIView swiped]: unrecognized selector sent to instance 0x1fdbd0c0

because it's looking for the "swiped" method on self.superview when I want it to look for the method on self, but I want the gesture to be detected on self.superview.

I'm also confused, if I set initWithTarget then why do I have to do addGestureRecognizer? What's the difference between those two things?

Upvotes: 0

Views: 218

Answers (2)

rmaddy
rmaddy

Reputation: 318794

Change this:

_swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self.superview action:@selector(swiped)];

to:

_swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swiped)];

The call to initWithTarget:action: specifies the class that gets told about the gesture events. The "target" must implement the "action" method.

The call to addGestureRecognizer: specifies which view the gesture must happen on.

In many cases these are the same but in your case they are different.

Upvotes: 2

shanegao
shanegao

Reputation: 3592

if you want to handle the gesture recognized in self, at first line, you should set self as the the receiver, not self.superview:

_swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swiped)];

then implement the swiped action:

-(void)swiped:(UIGestureRecognizer *)gestureRecognizer {
//enter code here
}

Upvotes: 0

Related Questions