Delta Engine Blog

AI, Robotics, multiplatform game development and Strict programming language

Passing touch events from UIScrollView to the parent UIViewController

This post is about Objective-C iPhone stuff!

Just because this took me some time to figure out (and might be useful in the future or for other people): In the iPhone SDK a UIScrollView class will eat up all touch events (touchesBegan, touchesEnded, touchesMove, etc.) and not pass them along to your view controller where all your view logic might be (like in my case). If you know this, you can just create a new class for each ScrollView and then have some of your logic there, but in my case all I want is to pass these events along to the UIViewController (like all the other controls behave like). For this reason I just created a simple class called PassTouchesScrollView, which looks like this:
//  PassTouchesScrollView.m
//  Simple helper class for UIScrollViews that need to pass touchesBegan to the
//  UIViewController above it (see all the Controller classes here).
#import "PassTouchesScrollView.h"

@implementation PassTouchesScrollView

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
	UIView *result = nil;
	for (UIView *child in self.subviews)
		if ([child pointInside:point withEvent:event])
			if ((result = [child hitTest:point withEvent:event]) != nil)
				break;

	return result;
}

- (void)dealloc
{
    [super dealloc];
}

@end

Note: This is only useful if you really do not need any touch events in the UIScrollView because even the scrolling drag touch events will be ignored and send to the UIViewController. If you want to be more selective, e.g. just pass the touchesEnded event on to the parents via:
-(void) touchesEnded: (NSSet *) touches withEvent: (UIEvent *) event
{
	// Pass to parent
	[super touchesEnded:touches withEvent:event];
	[self.nextResponder touchesEnded:touches withEvent:event];
}

References: Found helpful tips on StackOverflow and other sites (including this apple support forum).