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 down, but not left and right. Scroll view B matches the up and down of A, but can also scroll left and right. Scroll view A is always on the screen.
-----------------------------------------------------------
| | |
| | |
| | |
| A | B |
| | |
| scrolls | |
| up & down | scrolls all directions |
| | |
-----------------------------------------------------------
How would I make it so the the up and down scrolling (of either view) also makes the other view scroll in the same up-down direction? Or is there another method to do this?
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
throughsetContentOffset(offset, animated: false)
method causes cyclic calls of thescrollViewDidScroll(_ scrollView: UIScrollView)
delegate's method(see this question)Here is the solution that worked for me on iOS 11:
So instead of setting
contentOffset
we are usingbounds
property to sync the other scrollView with the one that was scrolled by the user. This way the delegate methodscrollViewDidScroll(_ scrollView: UIScrollView)
is not called cyclically and the scrolling happens very smooth and with inertia and bouncing effects as with a single scroll view.Set the delegate of scroll view A to be your view controller... then have...
If you want both to follow each other, then set delegate for both of them and use...
The above can be refactored to have a method which takes in two scrollviews and matches one to the other.
Swift 3 Version: