Some apps can benefit from being able to programatically scroll to a specific item in a ScrollView. Apple provides the means to do this with the ScrollViewReader. By calling scrollTo and providing it a position of the item, you can programatically have the items scrolled to the correct location.
This is particularly useful for apps such as chat messages, emails, or anything that lists items. For chat messages, you may want to scroll back up to the first unread message.
Lets take a look at how this works.
The example below creates a ScrollView with 50 items within.
struct ContentView: View {
@State private var offset = 35
var body: some View {
ScrollViewReader { proxy in
VStack {
Button("Scroll to Item \(offset)") {
withAnimation {
proxy.scrollTo(offset, anchor: .center)
}
}
ScrollView {
VStack(alignment: .leading) {
ForEach(0..<50) { i in
Text("Item \(i)")
.padding()
.id(i)
.background(i == offset ? Color.yellow.opacity(0.3) : Color.clear)
}
}
}
}
}
.padding()
}
}
Line 2 is used to set the offset of where you want to scroll to. You wouldn’t set this here normally as you would grab some value from the backend to determine where you want to jump to, but in this case, I just set it at 35 so the scroll view scrolls to the 35th item.
Line 5 we declare the ScrollViewReader and in the closure we are provided a ScrollViewProxy. We call it “proxy”.
We create a VStack next that puts a Button view up top and a ScrollView below it. The text of the Button is “Scroll to Item 35” or whatever you set the offset to earlier.
On lines 8 to 10 we use the ScrollViewProxy and call .scrollTo on it passing in the offset and setting the anchor to .center. The anchor provides the behaviour of the scroll action. .center scrolls the item to the center of the screen in this example.
The final task is on lines 12 to 21 where we create a ScrollView that contains a VStack (optional in this example and deals mostly with spacing). We have a ForEach that is set to show 50 items numbered 0 to 49 and then on line 17 we set the id to the index. In a real applications, perhaps an email app, you might set the id to a message ID and then rather than use the offset, you get the first unread message and scrollTo that message ID.
The last part is just used to colour the Text view based on if it is the offset.
If you run the app now then tapping the button at the top will scroll to item 35 in the list. Any questions, reach out below.
Leave a Reply
You must be logged in to post a comment.