Touchesbegan not detecting what is being touched

喜夏-厌秋 提交于 2019-12-01 11:32:18

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");
  }

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
    }
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!