Why is it that triggering a function from within a view updates the @State variable, but triggering that same function from another view does not?

Viewed 53

As I understand it has something to do with the fact that @State variables cannot be updated from outside a view. But I'm triggering a function within that same view, just from another view.

In my head this should work, but keen to understand why it doesn't and best way to update myValue from View2.swift

View1.swift

struct View1: View{
...

@State var myValue:Double


func myFunc(){

//Chang value of myValue
}


var body: some View{

Button{

myFunc() //clicking this updates myValue

}

...

View2.swift

...

Button{

View1().myFunc() //doesn't update value even though runs same function?

}

...
1 Answers

This was solved using ObservableObjects.

Related