Value from @State variable does not change

I have created a View that provides a convinient save button and a save method. Both can then be used inside a parent view.

The idea is to provide these so that the navigation bar items can be customized, but keep the original implementation.


Inside the view there is one Textfield which is bound to a @State variable. If the save method is called from within the same view everthing works as expected. If the parent view calls the save method on the child view, the changes to the @State variable are not applied.


Is this a bug in SwiftUI, or am I am missing something? I've created a simple playbook implementation that demonstrates the issue.


Thank you for your help.


import SwiftUI
import PlaygroundSupport

struct ContentView: View {
    // Create the child view to make the save button available inside this view
    var child = Child()

    var body: some View {
        NavigationView {
            NavigationLink(
                destination: child.navigationBarItems(
                    // Set the trailing button to the one from the child view.
                    // This is required as this view might be inside a modal
                    // sheet, and we need to add the cancel button as a leading
                    // button:
                    // leading: self.cancelButton
                    trailing: child.saveButton
                )
            ) {
                Text("Open")
            }
        }
    }
}

struct Child: View {
    // Store the value from the textfield
    @State private var value = "default"

    // Make this button available inside this view, and inside the parent view.
    // This makes sure the visibility of this button is always the same.
    var saveButton: some View {
        Button(action: save) {
            Text("Save")
        }
    }

    var body: some View {
        VStack {
            // Simple textfield to allow a string to change.
            TextField("Value", text: $value)

            // Just for the playground to change the value easily.
            // Usually it would be chnaged through the keyboard input.
            Button(action: {
                self.value = "new value"
            }) {
                Text("Update")
            }
        }
    }

    func save() {
        // This always displays the default value of the state variable.
        // Even after the Update button was used and the value did change inside
        // the textfield.
        print("\(value)")
    }
}

PlaygroundPage.current.setLiveView(ContentView())

Did you try in an App (to check), not in playground ?

Yes. That’s where I encountered the problem in the first place and then tried to reproduce it inside a Playground.

You need to set Enable Results To false Like mentioned in this answer https://developer.apple.com/forums/thread/677361?answerId=669301022#669301022
Value from @State variable does not change
 
 
Q