在我的.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);
}
有了这一切,它应该识别出我的图像,但没有任何事情发生。有什么想法吗?
答案 0 :(得分:2)
因此,由于UILabel
或UIImageView
等组件未设计为“可触摸”,因此要添加“可触摸”功能(如UITapRecognizer
),您必须设置他们的userInteractionEnabled
到YES
。
因此,即使您为UIImageView
(star1
)正确设置此属性,由于您将其添加为ratingLabelBody
的子视图,因此无法触发{{1} (UITapGestureRecognizer
)
您必须对imgTouchUp:
的{{1}}的父视图执行相同操作。
用代码翻译,你只需要这样做:
star1