![](/img/trans.png)
[英]My view doesn't update after modifying an object of a list inside an ObservableObject
[英]ObservableObject doesn't update view
我對 SwiftUI (和 Swift 我也有一段時間沒有接觸過)很陌生,所以請耐心等待:
我有這樣的看法:
import SwiftUI
import Combine
var settings = UserSettings()
struct Promotion: View {
@State var isModal: Bool = true
@State private var selectedNamespace = 2
@State private var namespaces = settings.namespaces
var body: some View {
VStack {
Picker(selection: $selectedNamespace, label: Text("Namespaces")) {
ForEach(0 ..< namespaces.count) {
Text(settings.namespaces[$0])
}
}
}.sheet(isPresented: $isModal, content: {
Login()
})
}
}
我在這里所做的是在啟動、登錄時調用登錄視圖,當成功時,我設置
變量設置
這樣在 LoginView
settings.namespaces = ["just", "some", "values"]
我的 UserSettings class 是這樣定義的
class UserSettings: ObservableObject {
@Published var namespaces = [String]()
}
根據我最近獲得的知識,我的登錄視圖正在設置我的 UserSettings class 的命名空間屬性。 由於此 class 是一個 ObservableObject,因此使用該 class 的任何視圖都應更新以反映更改。
但是,我的 Picker 仍然是空的。
那是因為根本的誤解,還是我只是少了一個逗號?
您必須在視圖中將ObservableObject
與ObservedObject
配對,以便通知視圖有關更改並刷新。
嘗試以下
struct Promotion: View {
@ObservedObject var settings = UserSettings() // << move here
@State var isModal: Bool = true
@State private var selectedNamespace = 2
// @State private var namespaces = settings.namespaces // << not needed
var body: some View {
VStack {
Picker(selection: $selectedNamespace, label: Text("Namespaces")) {
ForEach(namespaces.indices, id: \.self) {
Text(settings.namespaces[$0])
}
}
}.sheet(isPresented: $isModal, content: {
Login(settings: self.settings) // inject settings
})
}
}
struct Login: View {
@ObservedObject var settings: UserSettings // << declare only !!
// ... other code
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.