UIScrollView and cancel a zooming pinch gesture

2020-03-07 04:32发布

How do you forcibly cancel a zooming open pinch gesture on a UIScrollView, say when the user has zoomed "sufficiently" far to trigger a new action?

3条回答
Explosion°爆炸
2楼-- · 2020-03-07 05:05

A brute force solution i found is to remove and re-add the view that receives the touches, as my (sub)scrollview just did not end reacting to zooms as long as the user would not end the gesture.

In ScrollViews this is done commonly if you remove / add subviews as the user scrolls through a large content size, so there is not even the need to write additional code.

- (void)scrollViewDidZoom:(UIScrollView *)scrollView   
{
   if (scrollView.zoomScale < 0.65) 
   {
     // some actions
     [self myactionstodo];  
     // force cancel zoom gesture by usual reload (remove and re-add subviews)
     [self reloadSV:currentpage];  
   }
}
查看更多
叛逆
3楼-- · 2020-03-07 05:10

To prevent user-controller zooming and panning but still allow programmatic zooming and panning of a scrollview, the best approach is to override the UIScrollView's -addGestureRecognizer: method in a subclass.

-(void)addGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
{
    //Prevent any of the default panning and zooming controls from working
    gestureRecognizer.enabled = NO;
    [super addGestureRecognizer:gestureRecognizer];
    return;
}

Each gesture recognizer is simply disabled, for finer control (for ex. allowing the pan control but only allow zooming via a double tap for instance) you'd simply check the incoming gesture recognizer via -isKindOfClass: and disabling as appropriate.

-(void)addGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 
{
    //Prevent zooming but not panning
    if ([gestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]]) 
    {
        gestureRecognizer.enabled = NO;
    }
    [super addGestureRecognizer:gestureRecognizer];
    return;
}

Hope this helps.

查看更多
在下西门庆
4楼-- · 2020-03-07 05:14

How's this:

-(void)handlePinchGesture:(UIPinchGestureRecognizer *)sender
{
    if (![sender isEnabled])
    {
        [sender setEnabled:YES];
    }

    if (sender.state == UIGestureRecognizerStateChanged)
    {
        if (sender.scale > 2.0)
        {
            NSLog(@"Upper bound reached");
            [sender setEnabled:NO];

        }
        else if (sender.scale < 0.75)
        {
            NSLog(@"Lower bound reached");
            [sender setEnabled:NO];
        }
    }
}

Just register this selector(handlePinchGesture:) with the gesture recognizer. This will make a sort of "one-shot" pinch handler which stops when it reaches either the upper or lower threshold.

查看更多
登录 后发表回答