views:

677

answers:

2

I have some nested views like this:

First, there is an big UIView. Inside this, there is another UIView. And inside this, there is an MyNiceButtons class that inherits from UIView. So I have:

UIView > UIView > MyNiceButtons (= an UIView).

In detail, the UIView creates an UIImageView and adds it as a child view to itself, which represents an graphical button. So inside the MyNiceButtons class implementation, I have this code to handle a touch event on the fake button image:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject]; // i just need single touches

    // just to see which view is affected
    UIView *tview = [touch view];
    CGRect rect = tview.frame;
    rect.origin.x = rect.origin.x + 20.0f;
    tview.frame = rect;
    [tview setBackgroundColor:[UIColor yellowColor]];

    if ([touch view] == self.fakeButtonImageView) {
     NSLog(@"touch on fake button detected");
    }
}

All views in the hierarchy have userInteractionEnabled=YES. The touch arrives at the first view in the hierarchy (the parent of the parent).

UIView *tview = [touch view];

This returns just the parent of the parent, but not the UIImageView where the user actually tapped on.

What's the trick to recognize if the touch was on the button UIImageView?

+2  A: 

I would first suggest that you take a good look at what you can do with a Custom-type UIButton (can set images for various states). 95% of the time, this should address your needs.

If you have some other need, I can help you debug w/ hitTest, etc.

Andrew Pouliot
You're right about the UIButton, but for practise I want to know what's wrong here. It should actually work...
Thanks
A: 

Anyone have an answer to this...Im experiencing the same sorta issue...i've created 3 views...then a 4th main view, where i add the 3 views as subviews...then detect touch in the main view, but when doing the compare to see which of the three was touched, it seems like the 3views have a different coordinate reference vs the main view...

bigbucks
Oh, and just a side note...originally i implemented the 3 views as UIButtons in the main view...which works perfectly...I just think that the 3view as subviews into the main view, is actually to more "correct" way...so why wont Touch work correctly for something so functionally common?
bigbucks