Last active
July 9, 2024 12:56
-
-
Save SatoTakeshiX/1edf795ab9939e776c42290ac6821f2f to your computer and use it in GitHub Desktop.
Programmatically Scroll on SwiftUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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 | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
2024-07-09.21.50.01.mov