My problem is that i have (in SwiftUI) a ScrollView with an foreach inside. Know when the foreach loads all of my entries i want that the last entry is focused.
I did some google research, but i didn't find any answer.
ScrollView { VStack { ForEach (0..<self.entries.count) { index in Group { Text(self.entries[index].getName()) } } } }
1. Manual scroll to a position with the click of a button. 2. Auto-scroll to the bottom as soon as the view appears.
If you want to programmatically make SwiftUI's List move to show a specific row, you should embed it inside a ScrollViewReader . This provides a scrollTo() method on its proxy that can move to any row inside the list, just by providing its ID and optionally also an anchor.
A view that arranges its children in a line that grows vertically, creating items only as needed.
List view is a container that can present a scrollable list of views in SwiftUI. You can adjust its look, and it supports versatile actions and change its style depending on the platform.
I don't have enough reputation to post a comment yet, so here you go @Dam and @Evert
To scroll to the bottom whenever the number of entries in your ForEach
changes you can also use the same method with a ScrollViewReader
, as mentioned in the answer above, by adding the view modifier onChange
like so:
struct ContentView: View { let colors: [Color] = [.red, .blue, .green] var entries: [Entry] = Array(repeating: Entry(), count: 10) var body: some View { ScrollView { ScrollViewReader { value in ForEach(0..<entries.count) { i in Text(self.entries[i].getName()) .frame(width: 300, height: 200) .background(colors[i % colors.count]) .padding(.all, 20) } .onChange(of: entries.count) { _ in value.scrollTo(entries.count - 1) } } } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With