在SwiftUI列表视图中强制取消选择行

9q78igpj  于 2022-11-21  发布在  Swift
关注(0)|答案(3)|浏览(160)

我正在使用具有选择绑定的列表。我的期望是清除选择应更新列表,使其不具有任何选定行,但行UI仍保持选定状态。
下面是示例代码:

struct ContentView: View {
    @State private var selection: String?

    let names = [
        "a",
        "b",
        "c",
        "d"
    ]

    var body: some View {
        NavigationView {
            VStack {
                List(names, id: \.self, selection: $selection) { name in
                    Text(name)
                }

                Button("Deselect") {
                    self.selection = nil
                }
            }
        }
    }
}

我希望在按下按钮清除选择时,列表应更新为没有任何选择,但仍保持选中状态。

gv8xihay

gv8xihay1#

在iOS 16上工作

import SwiftUI

        struct listSelection: View {
            
            @State private var selection: String?
            
            let names = [
                "a",
                "b",
                "c",
                "d"
            ]
            
            var body: some View {
                NavigationView {
                    VStack {
                        List(names, id: \.self, selection: $selection) { name in
                            Text(name)
                        }
                        .id(UUID())
                        
                        Button("Deselect") {
                            selection = nil
                        }
                    }
                }
            }
        }

ogq8wdun

ogq8wdun2#

可以使用listRowBackground修改器基于选择设置背景。

struct ContentView: View {
    @State private var selection: String?

    let names = ["Munny", "Badnam", "Hui", "Tereliye"]

    var body: some View {
        NavigationView {
            VStack {
                List(names, id: \.self, selection: $selection) { name in
                    Text(name)
                        .listRowBackground(selection == name ? Color.black.opacity(0.2) : Color.white)
                }

                Button("Deselect") {
                    self.selection = .none
                }
            }
        }
    }
}

2eafrhcq

2eafrhcq3#

单行选择是为编辑模式设计的,您可以使用下面的代码打开它,它使取消选择工作:

struct ListTestView2: View {
    @State var editMode:EditMode = EditMode.active
    @State private var selection: String?
    
    let names = [
        "a",
        "b",
        "c",
        "d"
    ]
    
    var body: some View {
        NavigationView {
            VStack {
                List(names, id: \.self, selection: $selection) { name in
                    Text(name)
                }
                .environment(\.editMode, $editMode)
                Button("Deselect") {
                    self.selection = nil
                }
            }
        }
    }
}

相关问题