I want to automatically scroll to a particular view in a ScrollView on tap of a button. I know how to get it to work with ForEach views (there are examples of this online and on Stack overflow) but I cannot get it to work without the ForEach.
Here is an example of it working with a ForEach:
struct ContentView: View {
@State private var shouldScrollToBottom = false
var body: some View {
ScrollView {
VStack {
Button("Scroll to Bottom") {
shouldScrollToBottom = true
}
.padding()
ScrollViewReader { scrollViewProxy in
LazyVStack {
ForEach(0..<50) { index in
Text("Item (index)")
.frame(width: 200, height: 50)
.background(Color.blue)
.cornerRadius(10)
.padding()
.id(index)
}
}
.onChange(of: shouldScrollToBottom) { scrollToBottom in
if scrollToBottom {
withAnimation {
scrollViewProxy.scrollTo(49, anchor: .bottom)
}
shouldScrollToBottom = false
}
}
}
}
}
}
}
This code works.
But I want to do it with individual views (not with a ForEach).
Here is an example:
struct ContentView: View {
var body: some View {
VStack {
ScrollView {
Button("Scroll to view 4") {
}
.padding()
VStack {
Divider()
View1()
Divider()
}
VStack {
Divider()
View2()
Divider()
}
VStack {
Divider()
View3()
Divider()
}
VStack {
Divider()
View4()
Divider()
}
VStack {
Divider()
View5()
Divider()
}
}
}
}
}
In this view, how do I make it scroll to view 4 when the button is tapped?
2
Answers
It’s not fundamentally different from what you’d do with a
ForEach
. Just give your views anid
, and refer to the view you want to scroll to using thatid
.Technically, if you are only scrolling to the fourth view, you don’t need to add
id
s for the other views at all.The
id
can be anyHashable
thing. It doesn’t have to all beInt
s.According to Apple document
id
play vital role here. So you must provide unique id for individualView
So thatScrollViewReader
can detect and scroll correctly to thatView
.For Example: follow below code for you references