将 SwiftUI 列表滚动到新选择 [英] Scroll SwiftUI List to new selection

查看:34
本文介绍了将 SwiftUI 列表滚动到新选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您有一个允许单项选择的 SwiftUI 列表,您可以通过单击列表(大概这使它成为按键响应者)然后使用箭头键来更改选择.如果该选择到达可见区域的末尾,它将滚动整个列表以保持该选择可见.

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 the arrow keys. If that selection reaches the end of the visible area, it will scroll the whole list to keep the selection visible.

但是,如果选择对象以其他方式更新(例如使用按钮),列表将不会滚动.

However, if the selection object is updated in some other way (e.g. using a button), the list will not be scrolled.

当以编程方式设置时,有没有办法强制列表滚动到新选择?

Is there any way to force the list to scroll to the new selection when set programmatically?

示例应用:

import SwiftUI

struct ContentView: View {
    @State var selection: Int? = 0

    func changeSelection(_ by: Int) {
        switch self.selection {
        case .none:
            self.selection = 0
        case .some(let sel):
            self.selection = max(min(sel + by, 20), 0)
        }
    }

    var body: some View {
        HStack {
            List((0...20), selection: $selection) {
                Text(String($0))
            }
            VStack {
                Button(action: { self.changeSelection(-1) }) {
                    Text("Move Up")
                }
                Button(action: { self.changeSelection(1) }) {
                    Text("Move Down")
                }
            }
        }
    }
}

推荐答案

在适用于 iOs 14 和 MacOs Big Sur 的新版 SwiftUI 中,他们添加了使用新的 ScrollViewReader 以编程方式滚动到特定单元格的功能:

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)
                }
            }
        }
    }
}

然后你可以像这样使用.scrollTo()方法

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

value.scrollTo(8, anchor: .top)

信用:www.hackingwithswift.com

这篇关于将 SwiftUI 列表滚动到新选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆