R – Parent responds to child’s touch

cocoa-touchiphoneuiimageviewuiviewcontroller

I have a UIScrollView with subclassed UIImageViews in it. When one of the imageviews are clicked, I'd like the parent UIView (contains the scrollview) to receive the event in its

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

I can tell if the imageview was clicked by

if(CGRectContainsPoint(myScrollView.frame, location) == YES){...}

Assuming the imageview and scrollview are the same size. Or is there a better way to to know a particular imageview within the scrollview was tapped? The imageviews are created dynamically.

Best Answer

The approach I've used for this in the past is to fire off a notification when a subview has been touched, with the subview as the object posted with the notification. You can then have your container view listen for the appropriate notification, and perform whatever action is needed based on the UIView instance that was selected.

You'd post the notification within the subview's -touchesEnded:withEvent: method as follows:

[[NSNotificationCenter defaultCenter] postNotificationName:@"MySubviewWasTouched" object:self];

To set up listening for this notification, you'd place code like the following somewhere in the initialization of your view or view controller:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleSubviewTouch:) name:@"MySubviewWasTouched" object:nil];

remembering to remove the observer in your teardown code for the the view or controller.

Finally, you'd need to implement the method that processes the receipt of the notification (-handleSubviewTouch: in the example above):

- (void)handleSubviewTouch:(NSNotification *)note;
{
    UIView *subviewThatWasTouched = [note object];

    // Your touch-handling logic here
}
Related Topic