views:

173

answers:

4

Working in a ViewController that has a few views which were added to it as subviews and I have a touchesBegan method:

    UIImageView *testImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"test.png"]];
    testImage.frame = CGRectMake(0, 0, 480, 280);
    [self.view addSubview:testImage];

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint point;
    UITouch *touch = [touches anyObject];
    point.x = [touch locationInView:self.view].x;
    point.y = [touch locationInView:self.view].y;

    if ( point.y >= 280 && point.y <= 320 )
    {
     if ( point.x >= 0 && point.x <= 160 )
     {
      [self menu1];
     }

     if ( point.x >= 161 && point.x <= 320 )
     {
      [self menu2];
     }

     if ( point.x >= 321 && point.x <= 480 )
     {
      [self menu3];
     }
    }
}

My question is how in that method can I discern which view was clicked? I've been doing it with those screen coordinates, but that won't work if I also move those views at runtime.

Is there a way to see which view was clicked in the touches or event or in this code from above:

UITouch *touch = [touches anyObject];

Any help appreciated // :)

+1  A: 

I might be missing something, but wouldn't your "menuX" elements have their own rects describing their sizes and locations? Then all you do is ask if the point is within those rectangles.

Joshua Nozzi
+1  A: 

[touch view] will give you the view in which the touch initially occured (i.e., this view will remain the same even if the user moves the finger away from the view during the touch).

If that is not the behavior you require, use:

[self.view hitTest:[touch locationInView:self.view] withEvent:event];
Ole Begemann
This is cool, wish I could mark 2 answers as correct :)
Spanky
+1  A: 

Why are you implementing your own hit-testing? It's trivial just to place transparent buttons wherever you want them.

NSResponder
+2  A: 

Say you have a view controller with these ivars (connect to controls in Interface Builder)

IBOutlet UILabel *label;
IBOutlet UIImageView *image;

To tell if a touch hit these items or the background, view add this method to your view controller.

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

    if ([touch view] == label) {
     NSLog(@"touched the label");
    }

    if ([touch view] == image) {
     NSLog(@"touched the image");
    }

    if ([touch view] == self.view) {
     NSLog(@"touched the background");
    }
}

Any UIView subclass like a UIView, UILabel or UIImageView that you want to respond to touches must have the .userInteractionEnabled property set to YES.

willc2
This is great, thanks :)
Spanky