点击检测无法在UIImageView上运行 [英] Tap detection not working on UIImageView
问题描述
在我的.m文件中,我添加了:
In my .m file I added:
@property (strong, nonatomic) UIImageView *star1;
然后在我做的方法中:
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];
最后在我实施的.m文件中:
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?
推荐答案
因此,因为 UILabel
或<$等组件c $ c> UIImageView 不是设计为可触摸,添加可触摸功能(如 UITapRecognizer
),你有将 userInteractionEnabled
设置为 YES
。
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
.
所以,即使您为 UIImageView
( star1
)正确设置此属性,因为您将其添加为<$的子视图c $ c> ratingLabelBody ,你无法触发 UITapGestureRecognizer
( imgTouchUp:
) 。$
您必须对 star1
的父视图执行相同操作,即 ratingLabelBody
。
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];
这篇关于点击检测无法在UIImageView上运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!