UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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.

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.