UIScrollView: paging horizontally, scrolling vertically?

后端 未结 20 1399
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 09:09

How can I force a UIScrollView in which paging and scrolling are on to only move vertically or horizontally at a given moment?

My understanding is that

20条回答
  •  情深已故
    2020-11-27 09:40

    I've also had to solve this problem, and while Andrey Tarantsov's answer definitely has a lot of useful information for understanding how UIScrollViews work, I feel that the solution is a bit over-complicated. My solution, which doesn't involve any subclassing or touch forwarding, is as follows:

    1. Create two nested scroll views, one for each direction.
    2. Create two dummy UIPanGestureRecognizers, again one for each direction.
    3. Create failure dependencies between the UIScrollViews' panGestureRecognizer properties and the dummy UIPanGestureRecognizer corresponding to the direction perpendicular to your UIScrollView's desired scrolling direction by using UIGestureRecognizer's -requireGestureRecognizerToFail: selector.
    4. In the -gestureRecognizerShouldBegin: callbacks for your dummy UIPanGestureRecognizers, calculate the initial direction of the pan using the gesture's -translationInView: selector (your UIPanGestureRecognizers won't call this delegate callback until your touch has translated enough to register as a pan). Allow or disallow your gesture recognizer to begin depending on the calculated direction, which in turn should control whether or not the perpendicular UIScrollView pan gesture recognizer will be allowed to begin.
    5. In -gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:, don't allow your dummy UIPanGestureRecognizers to run alongside scrolling (unless you have some extra behavior you wanted to add).

提交回复
热议问题