I have the following code:
struct TestItem:Identifiable {
var id = UUID()
var index:Int
}
struct ContentView: View {
@State var testItems = [TestItem]()
let itemsUpperBound:Int = 1000
@State var trigger = false
var columnGridItems = [
GridItem(.flexible()),
GridItem(.flexible())
]
var body: some View {
VStack {
HStack {
Button {
trigger.toggle()
print("trigger: \(trigger)")
} label: {
Text("TEST")
.foregroundColor(.white)
.padding()
.background(.blue)
}
Spacer()
}
ScrollView(.horizontal) {
ScrollViewReader { sr in
LazyHGrid(rows: columnGridItems) {
ForEach(testItems) { ti in
Text("id \(ti.id)")
}
}
.border(.blue)
.onChange(of: trigger) { newValue in
withAnimation(.easeInOut(duration: 10)) {
let idx = Int.random(in: 0..<testItems.count)
let id = testItems[idx].id
print("will try to scroll to id: \(id)")
sr.scrollTo(id)
}
}
}
}
.border(.red)
}
.onAppear {
for i in 0..<itemsUpperBound {
testItems.append(TestItem(index: i))
}
}
}
}
I would like to animate the scroll view content offset, with whatever duration I'd like to set, so that the app would show the entire content of the scrollview without requiring the user to scroll it. In UIKit I could do it by animating the content offset, but, I am not sure how to do this in SwiftUI.
How can I animate the content offset of a scrollview in SwiftUI to achieve this type of animation?
I have edited the code to account for Asperi's comment and tried to use a ScrollReader. It does scroll to the desired item in the scrollview, but the duration is not working. I set it to 10 seconds, and it doesn't seem to do anything.
How can I animate the scroll using a custom duration I want?