因此,假设我有一个SwiftUI列表和Toggle(已大大简化):
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")
}
切换器应更改列表,在所有项目之间交换,仅在未完成的项目之间交换。这很完美。但是,我希望此功能起作用,以便当我按下按钮时,列表会立即更新并消失,而无需我重新切换切换开关。该怎么办?
答案 0 :(得分:1)
请注意,在处理大量数据时,列表仍然存在问题。在这里,您有一个示例可以完成您所要求的。我正在传递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")
}
}
}