BLACK FRIDAY SALE: Save big on all my Swift books and bundles! >>

Binding info from parent view to child view while also binding info from child view to parent view

Forums > SwiftUI

I posted about this earlier with a lot of code, but maybe I can simplify the question. Because structs are/were used in >95% of my swift education, I'm very uncomfortable with classes; I really have no idea when I'm supposed to use class+Published rather than struct+Binding/State.

I have a parent Search view with 1 textfield and 1 button to clear the field, and I have multiple child Tag views that are each a button for adding a word to the search field (and which "glow" after being pressed). The clear button should also un-glow all the Tag views.

The way I view Binding/State pairs is that the @Binding var is coded in the view where the action is taken to initiate a change and the @State var goes in the view in which the change is seen.

This would indicate that the parent Search view needs 2 @State var and 1 @Binding var, as does each child Tag view. But I run into an issue with the part of the diagram enclosed by the blue rectangle, because Binding variables are uninitialized, and I have no code for the Tag view to call on the Search view, e.g., SearchView(var1: ..., var2: $..., var3: $...).

The best I've been able to achieve acts perfectly except for one feature: let's say I have 4 tags (as opposed to 2 in the image); if I tap Tag1 (entering its label in the textfield and lighting the button) and Tag 2 (same), then tap clear (clearing the textfield and darkening Tag1 and Tag2), and then tap Tag3, Tag1 and Tag2 also light up for some reason.

I've also tried this by setting up the textfield as an ObservableObject, but I'm having more logic issues now than I did using all structs.

Should what I'm doing be achieved using only structs and Binding/State? or do I need some of the components to be classes so I can Publish? In which case, how do I determine which components should become classes and which should stay structs?

I feel like the Tag view needs to be a struct because each tag must remain unique and have its own values rather than all the Tag views pointing toward the same value.


Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.