Question

I am having a series of imageview arranged, and assigning a TapView recognizer to it

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
                                         initWithTarget:self action:@selector(action:)];
[tapRecognizer setNumberOfTouchesRequired:1];
[tapRecognizer setDelegate:self];
imageView.userInteractionEnabled = YES;
[imageView addGestureRecognizer:tapRecognizer];

and I have defined the selector as:

-(void) action:(id)sender
  {
    NSLog(@"TESTING TAP");
    NSLog (@"%d",[sender tag]);
  }

This is getting Crashed and i am getting Error message as:-

[UITapGestureRecognizer tag]: unrecognized selector sent to instance 0x145d0210

Was it helpful?

Solution

You can use this..

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
                                         initWithTarget:self action:@selector(action:)];
[tapRecognizer setNumberOfTouchesRequired:1];
[tapRecognizer setDelegate:self];
imageView.userInteractionEnabled = YES;
imageView.tag = 1111;
[imageView addGestureRecognizer:tapRecognizer];

And in action try this..

-(void) action:(id)sender
  {
    NSLog(@"TESTING TAP");
    UITapGestureRecognizer *tapRecognizer = (UITapGestureRecognizer *)sender;
    NSLog (@"%d",[tapRecognizer.view tag]);
  }

Explaination:

UITapGestureRecognizer has not property like tag. but it has property view, from this property you can access the view with which UITapGestureRecognizer was attached.

Hope it will help you

OTHER TIPS

Just Change your Selector Method with the following..and it will work

tapgesture will have the whole view which is tapped.. and then you can get the tag property from it as i have stated in following

-(void)action:(UITapGestureRecognizer *)tapGesture{

     NSLog(@"TESTING TAP");
        NSLog (@"%d",tapGesture.view.tag);

    }

Neither UITapGestureRecognizer nor UIGestureRecognizer declares a property or method called tag.

You can't use it. That's why you're getting the error.

On a related note. I really don't like using tag in general. There is always a better way to do what you're doing without using tag.

Swift equivalent of the accepted answer:

//use this to set up your tap gesture
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.reactToTap(sender:)))
imageView.tag = 33
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tapGesture)

This is the function which gets triggered by the tap:

@objc private func reactToTap(sender: UITapGestureRecognizer) {
            
    print("ImageView tag: ", sender.view?.tag ?? 0) //"ImageView tag: 33"
}

You cannot get tag property of UITapGestureRecognizer rather you have to get of its view's property,

You can try,

-(void)action:(id)sender
  {
     NSLog(@"TESTING TAP");
     NSLog (@"%d",[[sender view]tag]);

  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top