swift - 从 @Binding var 修改 @State var 不会刷新 SwiftUI 中的视图
问题描述
所以我有一个 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 var 不会重新加载视图?
有什么解决方法吗?
解决方案
好吧,这就像...解决方法...但是对于测试,请尝试
FilterBar(isEditing: $isEditing, selectedType: $selectedType)
if selectedType != .none {
EmptyView()
}
通常,将视图模型引入 asObservableObject
并filteredModels
在其中包含 as是正确的@Published
,因此您FilterBar
更改了该属性,这将自动刷新ParentView
.
推荐阅读
- python - Numpy:将 np.vectorize 应用于具有 dtype=object 的数组
- php - 如何遍历数据库中的所有用户并应用角色
- excel - 突然 pdf 导出代码不再起作用。我的代码有问题吗?
- powershell - 使用 PowerShell 开关正则表达式解析日志文件
- vba - If/Then 语句问题
- php - 使用可扩展实体创建捆绑包
- sql - sql将两列旋转到相同的列值
- github-api - GitHub:获取某个日期范围内存储库中更改文件的计数
- amazon-web-services - 通过 PUT 请求(Amazon S3 代理)将图像文件上传到 S3 时文件损坏
- git - 两个 Visual Studio 项目共享相同的代码和 Git