我已经找到了满足我需求的几乎完美的代码。但是有一个问题:
我想在每行中使用切换按钮而不是按钮。
@kontiki在此处发布的原始代码:SwiftUI hide list item from list item view
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")
}
}
}
我尝试使用像这样的切换来代替按钮:
Toggle(isOn: $item.isComplete) {
Text("Done")
}
按钮内有我不理解的if语句。我也尝试过在按钮之外使用这个let idx声明,以使其更易于使用切换(因为我不知道如何进行这种复杂的切换),但这也失败了。
答案 0 :(得分:1)
注意:列表中的Toggle控件更新存在已知问题。请注意。详细信息在Problems with layout of some rows in SwiftUI list主题中。
这是可行的方法。修改过的行在注释中标记。
import SwiftUI
struct Item: Identifiable, Equatable { // <<
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: self.$model.arr[self.model.arr.firstIndex(of: item)!]) // <<
}
}
}
}
struct Row: View {
@Binding var item: Item // <<
var body: some View {
HStack {
Toggle(isOn: $item.isComplete) {
Text("Done")
}
Text(item.isComplete ? "Complete" : "Not complete")
}
}
}