-1

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?

}

...
Gaz
  • 101
  • 1
  • 13
  • You are creating a new *instance* of the view `View1()` and calling the function on that. This is not the same instance of the view that you are seeing. You probably need a model object with an observable property that you can share between the two views. – Paulw11 Sep 12 '22 at 10:34
  • Thanks @Paulw11, I’ll look into models. To help my understanding, in what scenario might one want to create a new instance of a view? – Gaz Sep 12 '22 at 10:46
  • 1
    Since SwiftUI views are structs, and therefore immutable, new instances are created all the time. Whenever your state property changes, SwiftUI creates a new view instance to show the updated value. However, you would never create a new view instance outside of the view hierarchy. Ie when you say `HStack { View1() }` you are creating a new instance of the view in the view hierarchy and this is completely normal. Creating a new instance in a button action closure is pointless; the view isn't shown and will be discarded as soon as the closure exits – Paulw11 Sep 12 '22 at 11:04

1 Answers1

0

This was solved using ObservableObjects.

Gaz
  • 101
  • 1
  • 13
  • That's ok for model data but for view data I recommend sticking with `@State` and learning about `@Binding`, these give object-like semantics to structs. – malhal Sep 12 '22 at 15:53
  • I was really struggling to get @Binding working with TabView. – Gaz Sep 12 '22 at 16:11