Referencing a button when the action's sender

2020-06-23 09:41发布

问题:

I've got a button called myButton and I gave it a UIGestureRecognizer so that an IBAction is only run when myButton is pressed with two fingers:

UIGestureRecognizer  *tapper = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(twoFingerTap:)];
[(UITapGestureRecognizer *) tapper setNumberOfTouchesRequired:1];
[newTaskButton addGestureRecognizer:tapper];

Prior to adding the gesture recognizer, I could use sender to reference the button that was just pressed, however now sender is now the gesture recognizer. I still need to reference the button that was pressed...Is there any way to go about doing so? An easy method that returns whatever is using the gesture recognizer maybe? Thanks!

回答1:

The UIGestureRecognizer class has a view property representing the view the gesture recognizer is attached to, in your case, the button.

- (void)twoFingerTap:(UIGestureRecognizer *)sender {
    UIButton *myButton = (UIButton *)sender.view;
}