Skip to content

Instantly share code, notes, and snippets.

@SatoTakeshiX
Last active July 9, 2024 12:56
Show Gist options
  • Save SatoTakeshiX/1edf795ab9939e776c42290ac6821f2f to your computer and use it in GitHub Desktop.
Save SatoTakeshiX/1edf795ab9939e776c42290ac6821f2f to your computer and use it in GitHub Desktop.
Programmatically Scroll on SwiftUI
struct ContentView: View {
let colors: [Color] = [.red, .green, .blue]
@State
var model = ScrollModel()
var body: some View {
NavigationStack {
ScrollViewReader { value in
List {
ForEach(model.ids, id: \.self) { i in
Text("Example \(i)")
.font(.title)
.frame(maxWidth: .infinity, minHeight: 80)
.background(colors[i % colors.count])
}
}
.toolbar {
ToolbarItem {
Button(action: {
model.start()
}, label: {
Text("start timer")
})
}
}
.navigationTitle("Auto Scroll")
.onChange(of: model.forcusID) { oldValue, newValue in
withAnimation {
value.scrollTo(newValue, anchor: .top)
}
}
}
}
}
}
@Observable
final class ScrollModel {
let ids = Array(0..<100)
var forcusID: Int = 0
func start() {
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
if let max = self.ids.max(), max >= self.forcusID {
print(self.forcusID)
self.forcusID = self.forcusID + 1
}
}
}
}
@SatoTakeshiX
Copy link
Author

2024-07-09.21.50.01.mov

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment