Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Can I override pinch in/out behavior of UIScrollView?

I'm drawing a graph on a UIView, which is contained by a UIScrollView so that the user can scroll horizontally to look around the entire graph.

Now I want to zoom the graph when a user pinches in with two fingers, but instead of zooming in a view with the same rate for X and Y direction, I want to zoom only in the X direction by changing the X scale, without changing the Y scale.

I think I have to catch the pinch in/out gesture and redraw the graph, overriding the default zooming behavior.

But is there a way to do this?

I've been having a very difficult time to catch the pinch gesture on the UIScrollView, as it cancels the touches when it starts to scroll. I want the zooming to work even after the UIScrollView cancels the touches. :(

Thanks, Kura

like image 990
Taka Avatar asked Jun 30 '11 18:06

Taka


2 Answers

Although you cannot delete the existing pinch gesture recognizer, you can disable it and then add your own:

// Disable existing recognizer
for (UIGestureRecognizer* recognizer in [_scrollView gestureRecognizers]) {
    if ([recognizer isKindOfClass:[UIPinchGestureRecognizer class]]) {
        [recognizer setEnabled:NO];
    }
}

// Add our own
UIPinchGestureRecognizer* pinchRecognizer = 
  [[UIPinchGestureRecognizer alloc] initWithTarget:self 
                                            action:@selector(pinch:)];
[_scrollView addGestureRecognizer:pinchRecognizer];
[pinchRecognizer release];

Then in

- (void) pinch:(UIPinchGestureRecognizer*)recognizer { .. }

use

[recognizer locationOfTouch:0 inView:..]
[recognizer locationOfTouch:1 inView:..]

to figure out if the user is pinching horizontally or vertically.

like image 179
edsko Avatar answered Nov 15 '22 11:11

edsko


You should instead access the gestureRecognizers (defined in UIView), there are several of them being used by the scroll view,

figure out which one is the pinch recognizer and call removeGestureRecognizer: on the scroll view, then create your own and have it do the work, add it back with addGestureRecognizer:.

these are all public API, the recognizers and what order they are in are not (currently), so program defensively when accessing them

(this is a perfectly valid way to manipulate UIKit views, and Apple won't/shouldn't have issues with it - though they will not guarantee it works in any future release)

like image 44
bshirley Avatar answered Nov 15 '22 11:11

bshirley