简体   繁体   中英

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:

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

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

my UserSettings class is defined as such

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. Since this class is an ObservableObject, any view using that class should update to reflect the changes.

However, my Picker remains empty.

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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