below is a simple example of a sorted list of characters, an "add" button to randomly add an additional character to the list, and a list to display the content.
I would like to be able to set the scroll position of this list so that the most recent added character is always visible without requiring the user to scroll. I've tried many options discussed here & elsewhere.
What say you?
import SwiftUI
struct ContentView: View {
@State var myList = [myItem(name: "a"), myItem(name: "z")]
@State var selectRow: Set = [myItem(name: "foo")]
var body: some View {
VStack {
Text("Header")
Divider()
ScrollToView(myList: $myList, selectRow: $selectRow)
.frame(maxHeight: 300)
Text("Footer")
}
}
}
struct ScrollToView: View {
@Binding var myList: [myItem]
@Binding var selectRow: Set<myItem>
@State private var lastAdded: UUID?
var body: some View {
VStack {
Button(action: addLetter) {
Text("Add")
}
Divider()
VStack {
List(myList, selection: $selectRow) {
SelectableRow(myItem: $0, selectRow: self.$selectRow)
}
}
}
}
func addLetter() {
let randomInt = Int.random(in: 98..<122)
let s = String(UnicodeScalar(UInt8(randomInt)))
let newItem = myItem(name: s)
lastAdded = newItem.id
selectRow = [newItem]
myList.append(newItem)
myList.sort(by: { $0.name < $1.name })
}
}
struct SelectableRow: View {
var myItem: myItem
@Binding var selectRow: Set<myItem>
var isSelected: Bool {
selectRow.contains(myItem)
}
var body: some View {
HStack {
Text(self.myItem.name)
.foregroundColor(self.isSelected ? Color.red : Color.primary)
}
}
}
struct myItem: Identifiable, Hashable {
let id = UUID()
let name: String
}
Thank you for any help!