-4

I have three files: File A, File B and File C.

I want to change the value of an @State in File C from File B, but I would prefer to actually run the view in File C from File A.

Here are my files and code to help people understand the issue:

File A:

#import SwiftUI

struct ContentView: View {
    var body: some View {
        FileC()
    }
}

File B:

#import SwiftUI

struct FileB: View {
    var body: some View {
        Button (action: {
                variable = true // This is the variable I want to change.
        })
        {
        Image("Image")
        }
    }
}

File C:

#import SwiftUI

struct FileC: View {
@State var variable = false;
    var body: some View {
        if variable == true {
            Rectangle()
        }
    }
}

I have not tried anything that would resolve this issue as I have little experience in Swift and do not know what to do in this case. I hoped to access the variable from file B with something such as FileB().variable = true, but this only gave me various errors or did nothing at all.

I have read from other sources to use @Binding as an argument for when calling a view, but I want to be able to call the function without having that information available from the chosen file.

DischordDynne
  • 117
  • 15
  • 4
    State is a source of truth Binding is a tow way connection. SwiftUI isn’t like other frameworks you have to use wrappers to connect data. I suggest the SwiftUI tutorials there are other options like ObservableObjects. – lorem ipsum Feb 08 '23 at 01:28

1 Answers1

1

A source of truth, eg @State, needs to be in a common parent of all the Views it is needed. Pass down read access as let or write access as @Binding var.

To pass data up the hierarchy look at Preferences.

Another feature is to use closures, like how Button's action works.

malhal
  • 26,330
  • 7
  • 115
  • 133