SwiftUI List how to identify what item is selected on macOS

巧了我就是萌 提交于 2020-04-30 09:25:07

问题


Here is what I have based on this answer. The code currently allows the user to select a cell but I cannot distinguish which cell is selected or execute any code in response to the selection. In summary, how can I execute code based on the selected cell's name and execute on click. The cell currently highlights in blue where clicked, but I want to identify it and act accordingly based on that selection. Note: I am not looking to select the cell in editing mode. Also, how can I programmatically select a cell without click?

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



Here is a gif demoing the selection


回答1:


List selection works in Edit mode, so here is some demo of selection usage

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



回答2:


I found a workaround, but the text itself has to be clicked- clicking the cell does nothing:

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


来源:https://stackoverflow.com/questions/61450186/swiftui-list-how-to-identify-what-item-is-selected-on-macos

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!