16

I know that this is a very commonly asked question, but all of the answers on every website don't work! If you still don't know what I mean, then maybe this line of code will help you understand.


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:self.view];
    if (touch.view == nextbutton)
        [self performSelector:@selector(next)];
    if (touch.view == prevbutton)
        [self performSelector:@selector(previous)];
    if (touch.view == moreoptionsbutton)
        [self performSelector:@selector(moresettings)];
}

It doesn't do anything when you touch nextbutton, prevbutton, and more optionsbutton, which are UIImageViews by the way. I have also tried using isEqual: instead of ==, but that hasn't worked out either. Any suggestions?

Alex Cio
  • 6,014
  • 5
  • 44
  • 74
Flafla2
  • 691
  • 2
  • 11
  • 21

2 Answers2

35

You have to set userinteractionEnabled = YES for all your UIImageViews otherwise they will not receive touch events. Also change the line:

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

to

 UITouch *touch = [touches anyObject];
RunLoop
  • 20,288
  • 21
  • 96
  • 151
  • 1
    Thank you for the userinteractionEnabled = YES tip. I was banging my head to figure out why my UIImageView was not registering touches. – DenVog Dec 14 '12 at 18:18
2

I created a check to be sure its the view I expect to be clicked before going on.

if( [touch.view isKindOfClass:[Custom class]] ){
    CGPoint touchPoint = [touch locationInView:self.view];

    if( CGRectContainsPoint( self.customClassOne.frame, touchPoint )
       || CGRectContainsPoint( self.customClassTwo.frame, touchPoint ) ){
        [self touchOnCustomClass];
    }
}
Alex Cio
  • 6,014
  • 5
  • 44
  • 74