UIScrollView: paging horizontally, scrolling vertically?

后端 未结 20 1469
佛祖请我去吃肉
佛祖请我去吃肉 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:48

    I managed to solve this by implementing scrollViewDidBeginDragging(_:) and looking at the velocity on the underlying UIPanGestureRecognizer.

    NB: With this solution, every pan that would have been diagonal will be ignored by the scrollView.

    override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        super.scrollViewWillBeginDragging(scrollView)
        let velocity = scrollView.panGestureRecognizer.velocity(in: scrollView)
        if velocity.x != 0 && velocity.y != 0 {
            scrollView.panGestureRecognizer.isEnabled = false
            scrollView.panGestureRecognizer.isEnabled = true
        }
    }
    

提交回复
热议问题