Simultaneously Scrolling ScrollViews in SwiftUI | by David Steinacher | Mar, 2022

Simultaneous scrolling UIScrollViewutilizing UIKit can simply be achieved by utilizing the UIScrollViewDelegate . The concept is fairly easy: Observe the contentOffset of a UIScrollView and apply it to a different one when the worth adjustments.

Nonetheless, SwiftUI at present doesn’t present an API to realize the exact same.

As there are not any APIs to allow this we have to entry the underlying UIKit component and set the contentOffset there. That is the place SwiftUI-Introspect is useful by offering entry to the UIKit components.

After including Introspect to your venture, you possibly can entry UIKit components like this:

With that, we will now implement a element for concurrently scrolling UIScrollViews.

For simplicity let’s name this element SimultaneoulsyScrollViewHandler . We have to register all of the UIScrollViews we need to synchronize on this element to have the ability to observe and regulate their contentOffsets.

Discover a prepared to make use of Swift Bundle right here: SimultaneouslyScrollView

Now we have to get notified about contentOffset adjustments of the UIScrollView s of our array and apply it to all different registered UIScrollView s.

We are able to achive this by implementing the UIScrollViewDelegate :

With this new element, we will now return to our SwiftUI View and utilizing it in introspectScrollView as following:

See it in motion:

I like to recommend storing the simultaneouslyScrollViewHandler inside some view-model. E.g. an @ObservedObject or a @StateObject.

The above implementation accommodates a couple of points.

One is that the scrollViews Array by no means get’s cleared and can retain all UIScrollView s from all of the redraws of SwiftUI . This may be solved by utilizing some kind of a weak-reference-store.

This and different enhancements could be discovered on a last implementation on my GitHub profile:

More Posts