首页 > 解决方案 > 从 @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 不会重新加载视图?

有什么解决方法吗?

标签: swiftswiftui

解决方案


好吧,这就像...解决方法...但是对于测试,请尝试

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

通常,将视图模型引入 asObservableObjectfilteredModels在其中包含 as是正确的@Published,因此您FilterBar更改了该属性,这将自动刷新ParentView.


推荐阅读