UIScrollView and Multi-Touch zooming

Let's say you have a nice, big, hi-res photo you want to show to your user on the iPhone. No doubt you want to let your user zoom in to see details of the photo and scroll around, just like the built-in Photos.app.
Most of you would probably come up with something akin to the following structure using Interface Builder:

UIView

|
–UIScrollView
|
–UIImageView
If you are coding the UI by hand, the top level UIView would probably be omitted. This may or may not be relevant to the issue you'll be encountering. See my note at the end.
Now that the view structure is setup, you will probably discover that double tapping to zoom in/out is not implemented out of the box by Apple (surprise!).
"Ok", you thought to yourself, "I just need to implement the touch events in the controller and it will all work."
So you go ahead and added touch event code to the controller class, probably something like this:

– (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

UITouch *touch = [touches anyObject];

NSInteger tapCount = [touch tapCount];

if (tapCount == 2) {

[scrollView_ setZoomScale:zoomScale animated:YES];

}

}

When you run the code, you'll find that the touchesEnded method never get called!
Turns out this is actually by design from Apple. touchesEnded and other touch event methods are no-op methods by default. My guess is that this is probably a performance related design decision.
Regardless of why, here is what you need to do to 'fix' this. First, create a new class that inherits from UIScrollView. Then in this new subclass, implements the touch event method that you want to use and passes on the event to the next responder in the list. Like this:

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

{

[super touchesEnded:touches withEvent:event];

[self.nextResponder touchesEnded:touches withEvent:event];

}

This will pass on the touch event to the parent UIView in the hierarchy and thus calls the touch method in the controller.
Problem solved!
(One thing I haven't tried is to removed the top level UIView from the hierarchy, and link the UIScrollView to the view outlet in the controller. My hunch is that this may eliminate the need to subclass UIScrollView.)

Read and post comments

|

Send to a friend