Detecting horizontal scrolling in a UIScrollView using vertical scrolling

I have a UIScrollView with a size of about 600 pixels and a width of 320. Therefore, I allow the user to scroll vertically.

I am also trying to capture horizontal scrolls in a view. The problem is that when the user performs a horizontal move with some random vertical movement, the UIScrollView scrolls and my touchdesEnded delegate method are never called.

Here is my code:

- (void)touchesEnded: (NSSet *)touches withEvent: (UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint currentPosition = [touch locationInView:self];

    if (currentPosition.x + 35 < gestureStartPoint.x)
    {  
        NSLog(@"Right");
    }    
    else if (currentPosition.x - 35 > gestureStartPoint.x)
    {
        NSLog(@"Left");
    }    
    else if (!self.dragging)
    {
        [self.nextResponder touchesEnded: touches withEvent:event]; 
    }

    [super touchesEnded: touches withEvent: event];
}

Does anyone know how I can make this work even if there is vertical resistance?

+3
source share
3 answers

UIScrollView , , - , . , , , ; ( ).

, UIScrollView, - . , contentSize , frame, , UIScrollView, .

, . , . , UIScrollView , , . , .

, Apple UIScrollView docs:

, , . , touch-down, , , , . , . , . touchesShouldBegin:withEvent:inContentView:, pagingEnabled touchesShouldCancelInContentView: ( ), .

, , UIScrollView .

+4

@Tyler , UIScrollView touchhesBegan . , , , , UISCrollView ( nextResponder).

+1

Swift 4

viewDidLoad()

let leftGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(_:)))
leftGesture.direction = .left
leftGesture.delegate = self
view.addGestureRecognizer(leftGesture)

let rightGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(_:)))
rightGesture.direction = .right
rightGesture.delegate = self
view.addGestureRecognizer(rightGesture)

@objc func handleSwipe(_ sender: UISwipeGestureRecognizer) {
    // do swipe left/right based on sender.direction == .left / .right
}

UIGestureRecognizerDelegate

class MyViewController: UIViewController, UIGestureRecognizerDelegate

...

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
                       shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

The last step fixes the problem that when you move more than +/- 5 pixels along the Y axis, the Scroll view takes over and begins to scroll vertically.

0
source

Source: https://habr.com/ru/post/1718478/


All Articles