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())
}
}
}
}
ScrollViewReader
in iOS14 SwiftUI gains a new ability. To be able to scroll in a ScrollView up to a particular item with a given id
. There is a new type called ScrollViewReader
which works just like Geometry Reader
.
The code below will scroll to the last item in your View.
So this is your struct for 'Entry' I guess:
struct Entry {
let id = UUID()
func getName() -> String {
return "Entry with id \(id.uuidString)"
}
}
And the main ContentView:
struct ContentView: View {
var entries: [Entry] = Array(repeating: Entry(), count: 10)
var body: some View {
ScrollView {
ScrollViewReader { value in
ForEach(entries, id: \.id) { entry in
Text(entry.getName())
.frame(width: 300, height: 200)
.padding(.all, 20)
}
.onAppear {
value.scrollTo(entries.last?.id, anchor: .center)
}
}
}
}
}
Try to run this in the new version of SwiftUI announced at WWDC20. I think it is a great enhancement.