所以,假设我有一个 SwiftUI 列表和切换(高度简化(:
List {
Toggle(isOn: $isOn) {
Text("Toggle")
}
ForEach(arr) { item in
if isOn || !item.isComplete {
Row(item: item)
}
}
}
然后我的行:
HStack {
Button(action: {
self.item.isComplete.toggle() // isComplete is a Boolean value
}) {
Text("Button")
}
Text(item.isComplete ? "Complete" : "Not complete")
}
切换开关应更改列表,在所有项目和仅未完成项目之间交换。这非常有效。但是,我希望它起作用,以便当我按下按钮时,列表会立即更新并消失,而不必重新切换切换。如何做到这一点?
请注意,当涉及到大型数据集时,列表仍然是错误的。在这里,您有一个示例可以按照您的要求进行操作。我正在传递 ObservableObject,但您也可以将其放在环境中。这取决于你。
import SwiftUI
struct Item: Identifiable {
let id = UUID()
var isComplete: Bool = false
}
class Model: ObservableObject {
@Published var isOn: Bool = false
@Published var arr = [Item(isComplete: true), Item(isComplete: false), Item(isComplete: true), Item(isComplete: false), Item(isComplete: true), Item(isComplete: true)]
}
struct ContentView: View {
@ObservedObject var model = Model()
var body: some View {
List {
Toggle(isOn: $model.isOn) { Text("Toggle") }
ForEach(self.model.arr.filter { model.isOn ? true : $0.isComplete }) { item in
Row(item: item, model: self.model)
}
}
}
}
struct Row: View {
let item: Item
@ObservedObject var model: Model
var body: some View {
HStack {
Button(action: {
if let idx = self.model.arr.firstIndex(where: { $0.id == self.item.id }) {
self.model.arr[idx].isComplete.toggle()
self.model.isOn = false
}
}) {
Text("Button")
}
Text(item.isComplete ? "Complete" : "Not complete")
}
}
}