问题
I set three buttons. Every button is tagged 1...3.
My UITapGestureRecognizer works only once and only for first UIButton. Can't select other two options. Code:
- (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonTapped:)];
recognizer.delegate = self;
recognizer.cancelsTouchesInView = NO;
[recognizer setNumberOfTapsRequired:1];
[_btnNegative addGestureRecognizer:recognizer];
[_btnNeutral addGestureRecognizer:recognizer];
[_btnPositive addGestureRecognizer:recognizer];
}
And the buttonTapped:
method:
-(void)buttonTapped:(UITapGestureRecognizer *)recognizer
{
switch (((UIGestureRecognizer *)recognizer).view.tag)
{
case 1:
{
NSLog(@"Positive");
[_btnPositive setBackgroundImage:[UIImage imageNamed:@"checkedBox"] forState:UIControlStateNormal];
[_btnNegative setBackgroundImage:[UIImage imageNamed:@"UncheckedBox"] forState:UIControlStateNormal];
[_btnNeutral setBackgroundImage:[UIImage imageNamed:@"UncheckedBox"] forState:UIControlStateNormal];
_opinion=@"Positive";
break;
}
case 2:
{
NSLog(@"Negative");
[_btnNegative setBackgroundImage:[UIImage imageNamed:@"checkedBox"] forState:UIControlStateNormal];
[_btnPositive setBackgroundImage:[UIImage imageNamed:@"UncheckedBox"] forState:UIControlStateNormal];
[_btnNeutral setBackgroundImage:[UIImage imageNamed:@"UncheckedBox"] forState:UIControlStateNormal];
_opinion=@"Negative";
break;
}
case 3:
{
NSLog(@"Neutral");
[_btnNeutral setBackgroundImage:[UIImage imageNamed:@"checkedBox"] forState:UIControlStateNormal];
[_btnNegative setBackgroundImage:[UIImage imageNamed:@"UncheckedBox"] forState:UIControlStateNormal];
[_btnPositive setBackgroundImage:[UIImage imageNamed:@"UncheckedBox"] forState:UIControlStateNormal];
_opinion=@"Neutral";
break;
}
}
}
Only case:1
works. Other cases never get called. I rechecked the button tags and are ok 1...3. Your help is much appreciated.
回答1:
I had the same problem Try to assign a new UITapGestureRecognizer to each button:
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonTapped:)];
recognizer.delegate = self;
recognizer.cancelsTouchesInView = NO;
[recognizer setNumberOfTapsRequired:1];
[_btnNegative addGestureRecognizer:recognizer];
recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonTapped:)];
[_btnNeutral addGestureRecognizer:recognizer];
recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonTapped:)];
[_btnPositive addGestureRecognizer:recognizer];
回答2:
No, you can't reuse the same gesture recognizer. A gesture recognizer is designed to be attached to one and only one view.
来源:https://stackoverflow.com/questions/24245814/ios7-uitapgesturerecognizer-reuse-issue