Hello, SwiftUI entusiasts!
Recently, I've been working on a feature which involved a small full screen banner implementation with scrollable content and pagination. Since the amount of items were fixed and were small - I picked the ScrollView with HStack in it. Had no issues with rendering them right away - that was even great since from UX will be no loaders.
.scrollTargetLayout and .id were used to programmatically change items but I wanted to track position also (or selected item in our case) like in good old UIKit scrollview delegate. Fortunately, iOS 17 brings that modifier for our use case. But it didn't worked! Since all examples in blogposts and in Apple Docs were using Lazy containers that gave me a hint.
Common usage
Here is a code example that uses LazyVStack:
In Preview it looks like this:
All seems fine.
Non-Lazy Container
Switching to regular VStack. In my case we had only 4 items to display or you want to apply a CustomLayout. It stops tracking.
.id() modifier prevents in non-lazy container binding of .scrollPosition and it was confirmed by finding the same issue description on StackOverflow.
In that case we need to set .id() in ForEach explicitly no make the binding work again.
Thanks for reading and good luck!