How do I pass data from a child view to a parent view to another child view in SwiftUI?

You can use EnvironmentObject for stuff like this...

The nice thing about EnvironmentObject is that whenever and wherever you change one of it's variables, it will always make sure that every where that variable is used, it's updated.

Note: To get every variable to update, you have to make sure that you pass through the BindableObject class / EnvironmentObject on everyView you wish to have it updated in...

SourceRectBindings:

class SourceRectBindings: BindableObject {

    /* PROTOCOL PROPERTIES */
    var willChange = PassthroughSubject<Application, Never>()

    /* Seems Like you missed the 'self' (send(self)) */
    var sourceRect: CGRect = .zero { willSet { willChange.send(self) }
}

Parent:

struct ParentView: view {
    @EnvironmentObject var sourceRectBindings: SourceRectBindings

    var body: some View {
        childViewA()
            .environmentObject(sourceRectBindings)
        childViewB()
            .environmentObject(sourceRectBindings)
    }
}

ChildViewA:

struct ChildViewA: view {
    @EnvironmentObject var sourceRectBindings: SourceRectBindings

    var body: some View {

        // Update your frame and the environment...
        // ...will update the variable everywhere it was used

        self.sourceRectBindings.sourceRect = CGRect(x: 0, y: 0, width: 300, height: 400)
        return Text("From ChildViewA : \(self.sourceRectBindings.sourceRect)")
    }
}

ChildViewB:

struct ChildViewB: view {
    @EnvironmentObject var sourceRectBindings: SourceRectBindings

    var body: some View {
        // This variable will always be up to date
        return Text("From ChildViewB : \(self.sourceRectBindings.sourceRect)")
    }
}

LAST STEPS TO MAKE IT WORK

• Go into your highest view you want the variable to update which is your parent view but i usually prefer my SceneDelegate ... so this is how i usually do it:

let sourceRectBindings = SourceRectBindings()

• Then in the same class 'SceneDelegate' is go to where i specify my root view and pass through my EnviromentObject

window.rootViewController = UIHostingController(
                rootView: ContentView()
                    .environmentObject(sourceRectBindings)
            )

• Then for the last step, I pass it through to may Parent view

struct ContentView : View {

    @EnvironmentObject var sourceRectBindings: SourceRectBindings

    var body: some View {
        ParentView()
            .environmentObject(sourceRectBindings)
    }
}

If you run the code just like this, you'll see that your preview throws errors. Thats because it didn't get passed the environment variable. To do so just start a dummy like instance of your environment:

#if DEBUG
struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        ContentView()
            .environmentObject(SourceRectBindings())
    }
}
#endif

Now you can use that variable how ever you like and if you want to pass anything else other that the rect ... you can just add the variable to the EnvironmentObject class and you can access and update it


You did not mention how ChildViewB obtains its rect. That is, does it use a GeometryReader, or any other source. Whatever method you use, you can pass information upwards the hierachy in two ways: through a binding, or through preferences. And if geometry is involved, even anchor preferences.

For the first case, without seeing your implementation, you may be missing a DispatchQueue.main.async {} when setting the rect. This is because the change must occur after the view finished updating itself. However, I consider that a dirty, dirty trick and only use it while testing, but never on production code.

The second alternative (using preferences), is a more robust approach (and is preferred ;-). I will include the code for both approaches, but you should definetely learn more about preferences. I recently wrote an article, that you can find here: https://swiftui-lab.com/communicating-with-the-view-tree-part-1/

First Method: I do not recommend, passing geometry values upward the hierarchy, that will affect how other views draw. But if you insist, this is how you can make it work:

struct ContentView : View {
    @State var rectFrame: CGRect = .zero

    var body: some View {
        VStack {
            ChildViewA(rectFrame: $rectFrame)
            ChildViewB(rectFrame: rectFrame)
        }
    }
}

struct ChildViewA: View {
    @Binding var rectFrame: CGRect

    var body: some View {
        DispatchQueue.main.async {
            self.rectFrame = CGRect(x: 10, y: 20, width: 30, height: 40)
        }

        return Text("CHILD VIEW A")
    }
}

struct ChildViewB: View {
    var rectFrame: CGRect = CGRect.zero

    var body: some View {
        Text("CHILD VIEW B: RECT WIDTH = \(rectFrame.size.width)")
    }
}

Second Method: Using Preferences

import SwiftUI

struct MyPrefKey: PreferenceKey {
    typealias Value = CGRect

    static var defaultValue: CGRect = .zero

    static func reduce(value: inout CGRect, nextValue: () -> CGRect) {
        value = nextValue()
    }
}

struct ContentView : View {
    @State var rectFrame: CGRect = .zero

    var body: some View {
        VStack {
            ChildViewA()
            ChildViewB(rectFrame: rectFrame)
        }
        .onPreferenceChange(MyPrefKey.self) {
            self.rectFrame = $0
        }

    }
}

struct ChildViewA: View {
    var body: some View {
        return Text("CHILD VIEW A")
            .preference(key: MyPrefKey.self, value: CGRect(x: 10, y: 20, width: 30, height: 40))
    }
}

struct ChildViewB: View {
    var rectFrame: CGRect = CGRect.zero

    var body: some View {
        Text("CHILD VIEW B: RECT WIDTH = \(rectFrame.size.width)")
    }
}