Tap detection not working on UIImageView(点击检测在 UIImageView 上不起作用)
问题描述
在我的 .m 文件中我添加了:
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];
最后在我实现的 .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 或 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) 正确设置了此属性,因为您将其添加为 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 上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:点击检测在 UIImageView 上不起作用
基础教程推荐
- 如何从 logcat 中删除旧数据? 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
