开发者

How do I check to see if my subview is being touched?

I've been attempting to expand on a tutorial by trying to make Ryu animate only when he is touched. However, the touch is not even being registered and I believe it has something to do with it being a subview. Here is my code:

-(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 imageN开发者_如何学Pythonamed:@"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];
}

This code compiles fine, however, when touching or clicking on ryu, nothing happens. I've also tried

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

but that gives me this error: "Comparison of distinct Objective-C type 'struct UIImage *' and 'struct UIView *' lacks a cast." What am I doing wrong?


Is the UIView set up to receive touch events at all?

ryuView.userInteractionEnabled = YES;


touchesBegan is method of UIView class, and it should be implemented in subclass of UIView (or of UIImageView in your case). Not in some outer class where you implement animation block!

So ensure that you create subclass of UIImageView e.g. RyuImageView and implement touchesBegan method. Then you should inform your object with animation block that ryuView was touched. You can use delegate method for this. See answer Xcode: How to change Image on Touching at an Image (same Position)? as sample.

And yes, set UIImageView's userInteractionEnabled to YES because default value of this property of UIImageView is NO

do it either in initWith... method of RyuImageView:

self.userInteractionEnabled = YES;

or in your animation block class:

 ryuView.userInteractionEnabled = YES;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜