Making two UIScrollViews follow each others scrolling

前端 未结 4 1648
名媛妹妹
名媛妹妹 2020-12-12 19:54

How would I make two scroll views follow each others scrolling?

For instance, I have a scroll view (A) on the left of a screen, whose contents can scroll up and dow

4条回答
  •  有刺的猬
    2020-12-12 20:15

    I tried the Simon Lee's answer on iOS 11. It worked but not very well. The two scroll views was synchronized, but using his method, the scroll views would lost the inertia effect(when it continue to scroll after you release your finger) and the bouncing effect. I think it was due to the fact that setting the contentOffset through setContentOffset(offset, animated: false) method causes cyclic calls of the scrollViewDidScroll(_ scrollView: UIScrollView) delegate's method(see this question)

    Here is the solution that worked for me on iOS 11:

     // implement UIScrollViewDelegate method
        func scrollViewDidScroll(_ scrollView: UIScrollView) {
            if scrollView == self.scrollViewA {
                self.syncScrollView(self.scrollViewB, toScrollView: self.scrollViewA)
            }
            else if scrollView == self.scrollViewB {
                self.syncScrollView(self.scrollViewA, toScrollView: scrollViewB)
            }
        }
    
        func syncScrollView(_ scrollViewToScroll: UIScrollView, toScrollView scrolledView: UIScrollView) {
            var scrollBounds = scrollViewToScroll.bounds
            scrollBounds.origin.y = scrolledView.contentOffset.y
            scrollViewToScroll.bounds = scrollBounds
        }
    

    So instead of setting contentOffset we are using bounds property to sync the other scrollView with the one that was scrolled by the user. This way the delegate method scrollViewDidScroll(_ scrollView: UIScrollView) is not called cyclically and the scrolling happens very smooth and with inertia and bouncing effects as with a single scroll view.

提交回复
热议问题