ObservableObject不会更新视图

时间:2020-07-25 13:02:47

标签: ios swiftui observable

我对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 UserSettings: ObservableObject {
    @Published var namespaces = [String]()
}

根据我最近获得的知识,我的“登录”视图正在设置UserSettings类的namespaces属性。由于此类是ObservableObject,因此使用该类的任何视图都应更新以反映更改。

但是,我的选择器仍然为空。

是因为一个基本的误解,还是我只是想念一个逗号?

1 个答案:

答案 0 :(得分:1)

您必须在视图中将ObservableObjectObservedObject配对,以便通知视图并进行更改。

尝试以下

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
}