我一直在尝试用触摸的手柄来玩,并且触及了Ended。我基本上只是想在我的视图中创建一个图像。然后能够在用户触摸图像时执行某些操作。当我触摸图像时它会执行我的if语句中的代码。对我做错了什么的想法?
viewDidLoad中:
UIImage *image = [UIImage imageNamed:@"myimage1.png"];
imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0, 0, 320, 200);
[self.view addSubview:imageView];
imageViewsArray = [NSArray arrayWithObjects:imageView, nil];
touchesEnded:
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
// do this on touch
UIView *touchedView = [touch view];
if ([imageViewsArray indexOfObject:touchedView] != NSNotFound) {
// not not found means found!
NSLog(@"Got Touch!");
}
}
我也试过使用这个if语句:
if ([[touch view] isKindOfClass:[UIImageView class]]) {
NSLog(@"Got Touch 2!");
}
答案 0 :(得分:1)
如果您想收到关于点按图片视图的通知,我建议您使用UITapGestureRecognizer
更简单的方法。
// After initializing and adding your UIImageView:
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(handleTap:)];
[imageView addGestureRecognizer:gr];
- (void)handleTap:(UITapGestureRecognizer *)gr {
NSLog(@"Touched!");
}
如果您想坚持touchesEnded
,请尝试以下步骤:
imageViews
中的nil
数组是否不是touchesEnded
。[touch view]
以查看哪个视图正在接收触摸。答案 1 :(得分:1)
与DrummerB一样,我建议使用UITapGestureRecognizer
代替。请查看官方文档here,以便更好地了解它的工作原理,但主要的是将手势识别器与处理点击的视图相关联。在您的情况下,因为您正在处理UIImageView
,请确保您打开属性userInteractionEnabled
,默认情况下NO
设置为UIImageView
:换句话说,默认情况下,imageView不会拾取事件。