Scroll SwiftUI List to new selection

后端 未结 3 1721
执念已碎
执念已碎 2020-12-15 19:30

If you have a SwiftUI List with that allows single selection, you can change the selection by clicking the list (presumably this makes it the key responder) and then using t

3条回答
  •  眼角桃花
    2020-12-15 19:50

    In the new relase of SwiftUI for iOs 14 and MacOs Big Sur they added the ability to programmatically scroll to a specific cell using the new ScrollViewReader:

    struct ContentView: View {
        let colors: [Color] = [.red, .green, .blue]
    
        var body: some View {
            ScrollView {
                ScrollViewReader { value in
                    Button("Jump to #8") {
                        value.scrollTo(8)
                    }
    
                    ForEach(0..<10) { i in
                        Text("Example \(i)")
                            .frame(width: 300, height: 300)
                            .background(colors[i % colors.count])
                            .id(i)
                    }
                }
            }
        }
    }
    

    Then you can use the method .scrollTo() like this

    value.scrollTo(8, anchor: .top)
    

    Credit: www.hackingwithswift.com

提交回复
热议问题