从@Binding变量修改@State变量不是';t刷新SwiftUI中的视图
所以我有一个ParentView,它包含一个过滤器和一个列表。它看起来像这样:从@Binding变量修改@State变量不是';t刷新SwiftUI中的视图,swift,swiftui,Swift,Swiftui,所以我有一个ParentView,它包含一个过滤器和一个列表。它看起来像这样: 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 s
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变量不重新加载视图有什么原因吗
有什么解决办法吗?嗯,就像。。。解决方法。。。但对于测试,请尝试
FilterBar(isEditing: $isEditing, selectedType: $selectedType)
if selectedType != .none {
EmptyView()
}
一般来说,将视图模型引入为
observateObject
,并将filteredModels
作为@Published
,是正确的,因此您的FilterBar
更改了该属性,这将自动刷新父视图
,这是因为所选类型
未在正文
中的任何位置使用,计算属性过滤器模型
在此处并不重要@State
仅在视图主体中使用时才影响视图,否则它只是属性。@Asperi我想可能是这样的。。。它被用于我初始化过滤器栏的地方——但我想这还不够好?@Asperi是一个解决方案,如果它检查selectedType并始终为true或其他什么,则只添加一个无意义的,因此视图会重新加载?你能提供一个具有最小可运行代码的git吗?(包括你用过的所有类型)@Asperi我刚试过几天前你给我的答案,结果证明你是对的——它确实有效,我有别的东西让它看起来好像没有。如果你看到这个,你可以转寄给赏金。