点击检测在 UIImageView 上不起作用

Tap detection not working on UIImageView(点击检测在 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 上不起作用