Touchesbegan not detecting what is being touched

2019-02-19 19:18发布

I'm building a rotating banner using a NSTimer to keep track of the current image with the image being animated from 5 different images. I have a touchesBegan set up to keep handle the touch event on the banner if someone clicks it. My proof-of-concept works, but moving it into another project, it breaks.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [[event allTouches] anyObject];
if ([touch view] == myImageView){
    [self getImage];
    NSLog(@"%@", currentImage);
}
}

Now when I put break points into my project, it grabs the touch just fine, but when it gets to the if ([touch view] == myImageView) it doesn't detect that the image view is being touched.

2条回答
走好不送
2楼-- · 2019-02-19 19:43

First of all you have to set userInteractionEnabled to YES in your viewDidLoad method like below:

[myImageView setUserInteractionEnabled:YES];

Note that for the myImageView, checking User Interaction Enabled via Identity Inspector didn't work for me.

Then change

UITouch *touch = [[event allTouches] anyObject];

to

UITouch *touch = [touches anyObject];

so that the touchesBegan method looks like below:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    if ([touch view] == myImageView) {
       // place any code here when myImageView is touched
    }
 }
查看更多
唯我独甜
3楼-- · 2019-02-19 19:44

Not sure what would cause that but have you tried using a UIGestureRecognizer? Try something like the code below and see if the method gets called.

  //Add Gesture Recognizer
  UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self    action:@selector(imageSelected)];
  tapped.numberOfTapsRequired = 1;
  [theImageView addGestureRecognizer:tapped];

  //Memory Cleanup
  [tapped release];

 -(void)imageSelected
  {
    NSLog(@"Selected an Image");
  }
查看更多
登录 后发表回答