Reputation: 168
There are few answers on SO (UILongPressGestureRecognizer), but I'm unable to get the correct value with the following code, not sure what I'm doing wrong. Tried few more pages on SO and similar one more third party website tutorial but unable to get the exact button detail.
@property (nonatomic,strong) UILongPressGestureRecognizer *lpgr;
@property (strong, nonatomic) IBOutlet UIButton *button1;
@property (strong, nonatomic) IBOutlet UIButton *button2;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGestures:)];
self.lpgr.minimumPressDuration = 2.0f;
self.lpgr.allowableMovement = 100.0f;
[self.view addGestureRecognizer:self.lpgr];
}
- (void)handleLongPressGestures:(UILongPressGestureRecognizer *)gesture
{
if ([gesture isEqual:self.lpgr]) {
if (gesture.state == UIGestureRecognizerStateBegan)
{
if (gesture.view == self.button1) {
NSLog(@"Button 1 is pressed for long");
}else if(gesture.view == self.button2) {
NSLog(@"Button 2 is pressed for long");
}else{
NSLog(@"another UI element is pressed for long");
}
}
}
}
Every time button is press for long, I'm getting NSLog(@"another UI element is pressed for long");
Upvotes: 0
Views: 116
Reputation: 1461
The else statement is being hit every time because you are adding the gesture to the main view. Even when you are long pressing on the button the event is being passed up to the view where you are catching it. If you add the lines below in viewDidLoad it will fire on the buttons appropriately.
[self.button1 addGestureRecognizer:self.lpgr];
[self.button2 addGestureRecognizer:self.lpgr];
Upvotes: 1