gpt4 book ai didi

swift - 从 @Binding var 修改 @State var 不会刷新 SwiftUI 中的 View

转载 作者:行者123 更新时间:2023-12-04 10:55:42 27 4
gpt4 key购买 nike

所以我有一个包含 FilterBar 和 List 的 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 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 时,父 View 中的变量确实会更新,正如我所观察到的在调试器中 - 但是 View 不会重新加载。所以看起来好像仍然在应用旧的过滤器。

是否有任何原因更新此 @State var 不会重新加载 View ?

有什么解决方法吗?

最佳答案

嗯,这就像......解决方法......但是为了测试,尝试

FilterBar(isEditing: $isEditing, selectedType: $selectedType)
if selectedType != .none {
EmptyView()
}

一般来说,将 View 模型引入为 ObservableObject 是正确的。并有 filteredModels在它作为 @Published ,所以您的 FilterBar更改了该属性,这将自动刷新 ParentView .

关于swift - 从 @Binding var 修改 @State var 不会刷新 SwiftUI 中的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59218600/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com