Tap detection not working on UIImageView

荒凉一梦 提交于 2019-11-27 08:59:12

问题


In my .m file I added:

@property (strong, nonatomic) UIImageView *star1;

Then in a method I did:

UIImage *star1Image;
star1Image = [UIImage imageNamed:@"staryes"];
self.star1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
self.star1.tag = 800;
[self.star1 setImage:star1Image];
[ratingLabelBody addSubview:self.star1];

After a few lines not related to this I have:

[self.star1 setUserInteractionEnabled:YES];
UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imgTouchUp:)];
tapped.numberOfTapsRequired = 1;
[self.star1 addGestureRecognizer:tapped];

And finally in the .m file I have implemented:

-(void)imgTouchUp:(id)sender {
    NSLog(@"imgTouchUp");
    UITapGestureRecognizer *gesture = (UITapGestureRecognizer *)sender;
    NSLog(@"tap detected on %li", (long)gesture.view.tag);
}

With all this, it should recognize the tap on my image but nothing is happening. Any idea?


回答1:


So, since components like UILabel or UIImageView aren't design to be "touchable", to add a "touchable" feature (like a UITapRecognizer), you have to set their userInteractionEnabled to YES.

So, even if you set this property correctly for your UIImageView (star1), since you add it as a subview of ratingLabelBody, you couldn't trigger your UITapGestureRecognizer (imgTouchUp:).
You have to do the same to the parent view of your star1, which is ratingLabelBody.

Translated with code, you just had to do:

[ratingLabelBody setUserInteractionEnabled:YES];


来源:https://stackoverflow.com/questions/23765590/tap-detection-not-working-on-uiimageview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!