【问题标题】:Why won't my bound [String] not change my multi-select list SwiftUI为什么我的绑定 [String] 不会更改我的多选列表 SwiftUI
【发布时间】:2019-11-21 21:53:00
【问题描述】:

我正在尝试创建一个多选列表:

    @Binding var selection:[String]


List {
            ForEach(self.items, id: \.self) { item in
                MultipleSelectionRow(title: item, isSelected: self.selection.contains(item)) {
                    if self.selection.contains(item) {
                        self.selection.removeAll(where: { $0 == item }) <=== NO AFFECT
                    }
                    else {
                        self.selection.append(item). <=== NO AFFECT
                    }
                    self.queryCallback()

                }
            }//ForEach
                .listRowBackground(Color("TPDarkGrey"))
        }//list

我有一排是调用上述动作的按钮

struct MultipleSelectionRow: View {
    var title: String
    var isSelected: Bool
    var action: () -> Void

    var body: some View {

        Button(action: self.action) {
            HStack {
                Text(self.title)
                Spacer()

                if self.isSelected {
                    Image(systemName: "checkmark")
                }
            }
            .font(.system(size: 14))
        }
    }
}

为什么它不追加或远程绑定数组中的项目?通过视图似乎第二次改变了

【问题讨论】:

    标签: list swiftui


    【解决方案1】:

    我设法从您的代码中生成了一个有效的示例:

    我不知道你的其余代码是如何设置的,所以很遗憾我无法提示你任何事情。

    struct MultipleSelectionRow: View {
        var title: String
        var isSelected: Bool
        var action: () -> Void
    
        var body: some View {
    
            Button(action: self.action) {
                HStack {
                    Text(self.title)
                    Spacer()
    
                    if self.isSelected {
                        Image(systemName: "checkmark")
                    }
                }
                .font(.system(size: 14))
            }
        }
    }
    
    struct ContentView: View {
        @State var selection:[String] = []
        @State var items:[String] = ["Hello", "my", "friend", "did", "I", "solve", "your", "question", "?"]
    
        var body: some View {
            List {
                ForEach(self.items, id: \.self) { item in
                    MultipleSelectionRow(title: item, isSelected: self.selection.contains(item)) {
                        if self.selection.contains(item) {
                            self.selection.removeAll(where: { $0 == item })
                        }
                        else {
                            self.selection.append(item)
                        }
    
                    }
                }
                .listRowBackground(Color("TPDarkGrey"))
            }
        }
    }
    

    我希望这有助于澄清事情。

    【讨论】:

      猜你喜欢
      • 2020-04-13
      • 2017-02-20
      • 2019-11-18
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 1970-01-01
      • 2020-02-02
      • 2023-03-30
      相关资源
      最近更新 更多