Touch detection not working in UIImageView
In my .m file, I added:
@property (strong, nonatomic) UIImageView *star1;
Then in the 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 unrelated to this, I:
[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 of this, it should recognize a click on my image, but nothing happens. Any idea?
source to share
So, since components like UILabel
or UIImageView
are not "touch", to add a "tactile" function (for example UITapRecognizer
), you must install them userInteractionEnabled
in YES
.
So, even if you set this property correctly for your UIImageView
( star1
), since you add it as a subplot ratingLabelBody
, you won't be able to run your UITapGestureRecognizer
( imgTouchUp:
).
You have to do the same with the parent view of yours star1
, which is ratingLabelBody
.
Translated with code, you just had to do:
[ratingLabelBody setUserInteractionEnabled:YES];
source to share