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

前端 未结 4 1840
轮回少年
轮回少年 2020-12-19 13:21

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.

相关标签:
4条回答
  • 2020-12-19 13:59

    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.

    0 讨论(0)
  • 2020-12-19 14:01

    Edsko & bshirley answers are good, but they don't tell where to place the code.

    First, I placed it in viewDidLoad method, but no Pinch Gesture Recognizer was found in the scrollview (maybe because my scrollview is an IBOutlet).

    Then I tried in viewWillAppear or viewDidAppear and the UIPinchGestureRecognizer was here.

    0 讨论(0)
  • 2020-12-19 14:19

    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)

    0 讨论(0)
  • 2020-12-19 14:24

    You should be able to subclass UIScrollView and override the touchesBegan: method. Don't call [super touchesBegan:] but instead, adjust the zoom as you like:

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        //Anything you want. Probably you would want to store all the touches
        //or their values, so that you can compare them to the touches
        //in the touchesEnded: method, 
        //thus letting you know what the pinch amount was
    }
    

    If you like, you can judge whether it's a pinch or not, and if it's not, call the super method, and only handle it yourself for custom pinches.

    0 讨论(0)
提交回复
热议问题