所以我有一个ParentView,其中包含一个FilterBar和一个List。看起来像这样:
struct ParentView: View {
@State var listCellModels: [ListCellModel]
// Both these vars are passed to the FilterBar and adjusted by the FilterBar
@State var isEditing: Bool = false
@State var selectedType: FilterType = .none
// When selected type is changed, I need to reload the models in the list with the new filter
private var filteredModels: [ListCellModel] {
return listCellModels.filter{
(selectedType.rawValue == 0 || $0.approved.rawValue == selectedType.rawValue)
}
}
var body: some View {
VStack {
FilterBar(isEditing: $isEditing, selectedType: $selectedType)
// All the items in the list are buttons that display a custom view I had
// this works fine, and when isEditing is changed the view DOES update
List(filteredModels) { model in
Button(action: {
// Does a thing
}, label: {
ListViewCell(model: model, isEditing: self.$isEditing)
})
}
}
}
}
“我的过滤器”栏只是一个简单的HStack,带有几个用于修改变量的按钮
struct FilterBar: View {
@Binding var isEditing: Bool
@Binding var selectedType: FilterType
var body: some View {
HStack(alignment: .center) {
Button(action: {
self.selectedType = FilterType.init(rawValue: (self.selectedType.rawValue + 1) % 4)!
}, label: {
Text("Filter: \(selectedType.name)")
}).padding(.top).padding(.leading)
Spacer()
Button(action: {
self.isEditing = !self.isEditing
}, label: {
Text(!isEditing ? "Edit" : "Done")
}).padding(.top).padding(.trailing)
}
}
}
当我点击更改isEditing的按钮时,列表中的所有单元格都会更新以显示其“编辑”状态,但是当我点击按钮以更改selectedType时,父视图中的变量确实会更新,因为我在调试器中已经观察到-但是该视图不会重新加载。因此,看起来好像仍在应用旧过滤器。
是否有任何原因为什么更新此@State变量不会重新加载视图?
有没有解决方法?
答案 0 :(得分:2)
好吧,这就像...解决方法...但要进行测试,请尝试
FilterBar(isEditing: $isEditing, selectedType: $selectedType)
if selectedType != .none {
EmptyView()
}
通常,将视图模型引入为ObservableObject
并在其中将filteredModels
引入为@Published
是正确的,因此您的FilterBar
更改了该属性,该属性将自动刷新了ParentView
。