Adding Tap Gesture on UIImage

2019-04-19 18:31发布

问题:

I am trying to make clickable UIImage, where the user can click it then it'll animate...

i am working with the UIScrollVIew that's why i used the UITapGesture instead of touchesBegan, and it seems that UIGestureRecognizer is not compatible with UIImage...

am i right?

i keep receiving this error message

receiver type 'UIImage' for instance message does not declare a method with selector 'addGestureRecognizer'

is there any other way?

回答1:

You have to add TapGesture in UIImageView not UIImage

imgView.userInteractionEnabled = YES;

UITapGestureRecognizer *tapGesture1 = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(tapGesture:)];

tapGesture1.numberOfTapsRequired = 1;

[tapGesture1 setDelegate:self];

[imgView addGestureRecognizer:tapGesture1];

[tapGesture1 release];

You can response to the tap with the defined selector and do stuff there

- (void) tapGesture: (id)sender
{
    //handle Tap...
 }


回答2:

You have to add the gesture to UIImageView, not UIImage



回答3:

You can simply add a TapGestureRecognizer to a UIImageView. You have to use a UIImageView because gesture recognizer are only allowed to be added to views.

UIView *someView = [[UIView alloc] initWithFrame:CGRectZero];
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
tapRecognizer.numberOfTapsRequired = 1;
[someView addGestureRecognizer:tapRecognizer];

You can response to the tap with the defined selector and do stuff there

- (void)tapAction:(UITapGestureRecognizer *)tap
{
    // do stuff
}


回答4:

Try with UIButton instead of UIIMage and make the UIButton type custom. And on clicking the same you can show the animation.