点击检测不适用于UIImageView

时间:2014-05-20 16:46:16

标签: ios uiimageview uitapgesturerecognizer

在我的.m文件中,我添加了:

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

在几行与此无关之后,我有:

[self.star1 setUserInteractionEnabled:YES];
UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imgTouchUp:)];
tapped.numberOfTapsRequired = 1;
[self.star1 addGestureRecognizer:tapped];

最后在我实现的.m文件中:

-(void)imgTouchUp:(id)sender {
    NSLog(@"imgTouchUp");
    UITapGestureRecognizer *gesture = (UITapGestureRecognizer *)sender;
    NSLog(@"tap detected on %li", (long)gesture.view.tag);
}

有了这一切,它应该识别出我的图像,但没有任何事情发生。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

因此,由于UILabelUIImageView等组件未设计为“可触摸”,因此要添加“可触摸”功能(如UITapRecognizer),您必须设置他们的userInteractionEnabledYES

因此,即使您为UIImageViewstar1)正确设置此属性,由于您将其添加为ratingLabelBody的子视图,因此无法触发{{1} (UITapGestureRecognizer) 您必须对imgTouchUp:的{​​{1}}的父视图执行相同操作。

用代码翻译,你只需要这样做:

star1