gpt4 book ai didi

swiftui - @Published 属性不从嵌套 View 模型更新 View - SwiftUI

转载 作者:行者123 更新时间:2023-12-04 08:25:49 25 4
gpt4 key购买 nike

当我有一个嵌套在另一个 View 模型中的 View 模型时,我不确定为什么我的 View 没有得到更新。我的理解是, subview 模型中的 @Published 属性会触发父 View 模型的更改,从而将更改推送到 UI。
这是 subview 模型:

class FilterViewModel : ObservableObject, Identifiable {

var id = UUID().uuidString
var name = ""
var backgroundColour = ""
@Published var selected = false

private var cancellables = Set<AnyCancellable>()

init(name: String){
self.name = name

$selected.map { _ in
self.selected ? "Orange" : "LightGray"
}
.assign(to: \.backgroundColour, on: self)
.store(in: &cancellables)
}

func changeSelected() {

self.selected = !self.selected
}
}
以下按预期工作,单击按钮后,背景颜色会发生变化。
struct ContentView: View {

@ObservedObject var filterVM = FilterViewModel(name: "A")


Button(action: { filterVM.changeSelected()}, label: {
Text(filterVM.name)
.background(Color(filterVM.backgroundColour))
})
}
但是,我想要一组过滤器 View 模型,所以尝试过:
class FilterListViewModel: ObservableObject {

@Published var filtersVMS = [FilterViewModel]()

init(){
filtersVMS = [
FilterViewModel(name: "A"),
FilterViewModel(name: "B"),
FilterViewModel(name: "C"),
FilterViewModel(name: "D")
]
}
}
但是,单击按钮时不会更新以下 View
struct ContentView: View {

@ObservedObject var filterListVM = FilterListViewModel()

Button(action: { filterListVM[0].changeSelected()}, label: {
Text(filterListVM[0].name)
.background(Color(filterListVM[0].backgroundColour))
})
}

最佳答案

替代解决方案是为您的子模型使用分离 View :

struct FilterView: View {
@ObservedObject var filterVM: FilterViewModel

var body: some View {
Button(action: { filterVM.changeSelected()}, label: {
Text(filterVM.name)
.background(Color(filterVM.backgroundColour))
})
}
}
所以现在在父 View 中我们可以将它用作
struct ContentView: View {

@ObservedObject var filterListVM = FilterListViewModel()

// ...

FilterView(filterVM: filterListVM[0])
}

关于swiftui - @Published 属性不从嵌套 View 模型更新 View - SwiftUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65269802/

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