SwiftUI List 如何识别在 macOS 上选择了什么项目

SwiftUI List how to identify what item is selected on macOS

这是我根据 得出的结果。该代码当前允许用户 select 一个单元格,但我无法区分 哪个 单元格被 selected 或执行任何代码以响应 select离子。总之,我如何根据 selected 单元格的名称执行代码并在单击时执行。该单元格当前在单击的位置以蓝色突出显示,但我想识别它并根据 selection 采取相应的行动。注意:我没有在编辑模式下查看 select 单元格。另外,如何以编程方式 select 一个单元格而无需点击?

struct OtherView: View {
    @State var list: [String]
    @State var selectKeeper = Set<String>()

    var body: some View {
        NavigationView {
            List(list, id: \.self, selection: $selectKeeper) { item in
                Text(item)
            }
        }
    }
}



这是演示 selection 的 gif

列表选择在编辑模式下工作,所以这里是选择使用的一些演示

struct OtherView: View {
    @State var list: [String] = ["Phil Swanson", "Karen Gibbons", "Grant Kilman", "Wanda Green"]
    @State var selectKeeper = Set<String>()

    var body: some View {
        NavigationView {
            List(list, id: \.self, selection: $selectKeeper) { item in
                if self.selectKeeper.contains(item) {
                    Text(item).bold()
                } else {
                    Text(item)
                }
            }.navigationBarItems(trailing: HStack {
                if self.selectKeeper.count != 0 {
                    Button("Send") {
                        print("Sending selected... \(self.selectKeeper)")
                    }
                }
                EditButton()
            })
        }
    }
}

我找到了解决方法,但必须单击文本本身 - 单击单元格没有任何作用:

struct OtherView: View {
    @State var list: [String]
    @State var selectKeeper = Set<String>()

    var body: some View {
        NavigationView {
            List(list, id: \.self, selection: $selectKeeper) { item in
                Text(item)
                  .onTapGesture {
                     print(item)
                  }
            }
        }
    }
}

为了让您免去阵痛:

import SwiftUI

struct ContentView: View {
    @State private var selection: String?
    let list: [String] = ["First", "Second", "Third"]
    
    var body: some View {
        NavigationView {
            HStack {
                List(selection: $selection) {
                    ForEach(list, id: \.self) { item in
                        VStack {
                            Text(item)
                        }
                    }
                }
                TextField("Option", text: Binding(self.$selection) ?? .constant(""))
            }
            .frame(minWidth: 100, maxWidth: .infinity, minHeight: 100, maxHeight: .infinity)
        }
    }
}

此解决方案解决了@Isaac 提出的问题。

screenshot

我的 2 美分用于自定义选择和操作 适用于 swift 5.1 / iOS14:

见:

https://gist.github.com/ingconti/49497419e5edd84a5f3be52397c76eb4

我留下了很多调试“打印”..以便更好地理解。