shane
shane

Reputation: 1863

UILongPressGestureRecognizer on UIButton not working

I have a longpress gesture recognizer that I create in ViewDidLoad then attach to a button like this, the button is created in the storyboard and linked to my class.

UILongPressGestureRecognizer *hold = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(secretChange:)];
hold.minimumPressDuration = 5.0;
hold.delegate = self;

[_button addGestureRecognizer:hold];

The class conforms to the GestureRecognizer protocol and I have my selector here

- (void)secretChange:(UILongPressGestureRecognizer *)sender {
    // Some stuff
    NSLog(@"Secret");
}

The selector is not being called and I cannot figure out why, this seems to be the code everyone gives out on the internet, I have tried removing the minimum duration to make sure I didn't accidentally set it ridiculously long

UPDATE: I am actually adding this gesture recognizer to multiple buttons like this

[_button1 addGestureRecognizer:hold];
[_button2 addGestureRecognizer:hold];
[_button3 addGestureRecognizer:hold];

What is happening is the gesture recognizer is only being applied to the last button I add it to. How do I get the gesture recognizer added to ALL the buttons? Do I need to make a new one for every button?

Upvotes: 1

Views: 537

Answers (1)

xuzhe
xuzhe

Reputation: 5120

You should have three instance of UILongPressGestureRecognizer.

Before add a gesture recognizer to a new view, the addGestureRecognizer method will remove the gesture recognizer from the view it has been attached to.

Upvotes: 4

Related Questions