Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

ios - Tap detection not working on UIImageView

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...