如何检查我的子视图是否被触摸?

时间:2010-03-31 21:20:48

标签: iphone touch subview

我一直在努力扩展一个教程,试图让Ryu动画只有在他被触动时。然而,触摸甚至没有被注册,我相信它与它是一个子视图有关。这是我的代码:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
 UITouch *touch = [touches anyObject];

 if([touch view] == ryuView){
  NSLog(@"Touch");
 } else {
  NSLog(@"No touch");
 }
}

-(void) ryuAnims{
 NSArray *imageArray = [[NSArray alloc] initWithObjects:
         [UIImage imageNamed:@"1.png"],
         [UIImage imageNamed:@"2.png"],
         [UIImage imageNamed:@"3.png"],
         [UIImage imageNamed:@"4.png"],
         [UIImage imageNamed:@"5.png"],
         [UIImage imageNamed:@"6.png"],
         [UIImage imageNamed:@"7.png"],
         [UIImage imageNamed:@"8.png"],
         [UIImage imageNamed:@"9.png"],
         [UIImage imageNamed:@"10.png"],
         [UIImage imageNamed:@"11.png"],
         [UIImage imageNamed:@"12.png"],
         nil];

 ryuView.animationImages = imageArray;
 ryuView.animationDuration = 1.1;
 [ryuView startAnimating];


}



-(void)viewDidLoad {
       [super viewDidLoad];

       UIImageView *image = [[UIImageView alloc] initWithFrame:
        CGRectMake(100, 125, 150, 130)];
 ryuView = image;


 ryuView.image = [UIImage imageNamed:@"1.png"];
 ryuView.contentMode = UIViewContentModeBottomLeft; 
 [self.view addSubview:ryuView];
        [image release];
}

此代码编译良好,但是,当触摸或点击ryu时,没有任何反应。我也试过了

if([touch view] == ryuView.image) 

但是这给了我这个错误:“不同的Objective-C类型'struct UIImage *'和'struct UIView *'的比较没有强制转换。”我做错了什么?

2 个答案:

答案 0 :(得分:1)

UIView是否设置为完全接收触摸事件?

ryuView.userInteractionEnabled = YES;

答案 1 :(得分:0)

touchesBegan UIView 类的方法,它应该在 UIView (或 UIImageView 在你的情况下)。不在你实现动画块的外部类中!

因此,请确保您创建 UIImageView 的子类,例如 RyuImageView 并实施 touchesBegan 方法。然后你应该通过动画块告知你的对象ryuView被触摸了。您可以使用委托方法。请将答案Xcode: How to change Image on Touching at an Image (same Position)?视为样本。

是的,将UIImageView的 userInteractionEnabled 设置为 YES ,因为UIImageView的此属性的默认值为

在RyuImageView的initWith ...方法中执行:

self.userInteractionEnabled = YES;

或在动画块类中:

 ryuView.userInteractionEnabled = YES;