简体   繁体   中英

SwiftUI - Conditional based on ObservedObject doesn't work in subsequent Views

I have a very simple app which contains two views that are tied together with a NavigationLink . In the first view, ContentView , I can see updates to my ObservedObject as expected. However, when I go to the next View , it seems that the code based on the ObservedObject does not recognize changes.

ContentView.swift (The working view):

import SwiftUI

struct ContentView: View {
    @ObservedObject var toggleObject = ToggleObject()

    var body: some View {
        NavigationView {
            VStack(spacing: 15) {
                Toggle(isOn: self.$toggleObject.isToggled) {
                    Text("Toggle:")
                }

                if self.toggleObject.isToggled == true {
                    Text("ON")
                }
                else {
                    Text("OFF")
                }

                NavigationLink(destination: ShowToggleView()) {
                    Text("Show Toggle Status")
                }
            }
        }
    }
}

ShowToggleView.swift (The view that does not behave as I expect it to):

import SwiftUI

struct ShowToggleView: View {
    @ObservedObject var toggleObject = ToggleObject()

    var body: some View {
        Form {
            Section {
                if self.toggleObject.isToggled {
                    Text("Toggled on")
                }
                else {
                    Text("Toggled off")
                }
            }
        }
    }
}

All of this data is stored in a simple file, ToggleObject.swift:

import SwiftUI

class ToggleObject: ObservableObject {
    @Published var isToggled = false
}

When I toggle it on in the first View I see the text "ON" which is expected, but when I go into the next view it shows "Toggled off" no matter what I do in the first View ... Why is that?

Using Xcode 11.5 and Swift 5

You are almost doing everything correct. However, you are creating another instance of ToggleObject() in your second view, which overrides the data. You basically only create one ObservedObject and then pass it to your subview, so they both access the same data.

Change it to this:

struct ShowToggleView: View {
    @ObservedObject var toggleObject : ToggleObject

And then pass the object to that view in your navigation link...

NavigationLink(destination: ShowToggleView(toggleObject: self.toggleObject)) {
    Text("Show Toggle Status")
}

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