0

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!

DHalonen
  • 31
  • 4
  • Possible solution in [How to scroll List programmatically in SwiftUI?](https://stackoverflow.com/questions/60855852/how-to-scroll-list-programmatically-in-swiftui) – Asperi Jun 06 '20 at 16:38
  • You can try the solution from this article: https://lostmoa.com/blog/ScrollListToRowInSwiftUI/ – Natalia Panferova Jun 06 '20 at 23:12
  • lostmoa ROCKS! That solution requires almost no code changes to the demo and works perfectly. @Asperi - that solution didn't work with a view of height 300. It appears the geometry is assuming a full screen. Natalia's solution is awesome! Thank you very much! – DHalonen Jun 07 '20 at 04:10

0 Answers0