简体   繁体   中英

UI Tap Gesture Recognizer Not working does not know which View it was tapped

I have 6 different views and I have given them tags as 1,2,3,4,5,6. I added UITapGestureRecogniser from object Library on to the storyboard and made all 6 views gestureRecognizers of it by CTRL+Dragging from views to that UITapGestureRecogniser . Now in following method I am trying to get tag by tapping different views.

 - (IBAction)colorTapRecognizer:(UITapGestureRecognizer *)sender {
        UIView *tappedView= sender.view;
        NSLog(@"%d",tappedView.tag  );

    }

but it always shows me the same tag. ie if i tapped and it was 3 first time, it will be same by tapping other views as well.

Each View requires its own Gesture Recognizer set. Here is a piece of code that should work for you.

-(void)addTapGesturesToViews
{
    int maxViewTag = 6; // tags must be consective (are in your case)
    for(int i =1; i<= maxViewTag;i++)
    {
        UIView * view = [self.view viewWithTag:i];
        UITapGestureRecognizer * tapGest = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(colorTapRecognizer:)];
        tapGest.numberOfTapsRequired = 1;
        [view addGestureRecognizer:tapGest];
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM