简体   繁体   English

ObservableObject 不更新视图

[英]ObservableObject doesn't update view

I'm pretty new to SwiftUI (and Swift I haven't touch for a while either) so bear with me:我对 SwiftUI (和 Swift 我也有一段时间没有接触过)很陌生,所以请耐心等待:

I have this view:我有这样的看法:

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()
        })
    }
}

What I do here, is to call a Login view upon launch, login, and when successful, I set the我在这里所做的是在启动、登录时调用登录视图,当成功时,我设置

var settings变量设置

as such in the LoginView这样在 LoginView

settings.namespaces = ["just", "some", "values"]

my UserSettings class is defined as such我的 UserSettings class 是这样定义的

class UserSettings: ObservableObject {
    @Published var namespaces = [String]()
}

According to my recently obtained knowledge, my Login view is setting the namespaces property of my UserSettings class.根据我最近获得的知识,我的登录视图正在设置我的 UserSettings class 的命名空间属性。 Since this class is an ObservableObject, any view using that class should update to reflect the changes.由于此 class 是一个 ObservableObject,因此使用该 class 的任何视图都应更新以反映更改。

However, my Picker remains empty.但是,我的 Picker 仍然是空的。

Is that because of a fundamental misunderstanding, or am I just missing a comma or so?那是因为根本的误解,还是我只是少了一个逗号?

You have to pair ObservableObject with ObservedObject in view, so view is notified about changes and refreshed.您必须在视图中将ObservableObjectObservedObject配对,以便通知视图有关更改并刷新。

Try the following尝试以下

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM