MatterGoal
MatterGoal

Reputation: 16430

SwiftUI: what substitutes the Delegate protocol?

Let's consider one of the most basic flow available, where you have a view with data that is filled using other secondary views. i.e. Settings.

In the Settings view we have 2 items displayed:

SETTINGS
A - Pick a Color 
B - Pick a Country 

When user taps one of the items, the App will present a new view that can be used to select a color or another view that can be used to select a country.

When the user is done with one of the selection views, the Selection View is closed and the selection is passed back to the Settings view that now displays the new info:

SETTINGS
A - Green 
B - Spain

With delegates and protocols we can easily implement this code just putting the Settings view as delegate for the Colors and the Countries view and implementing a specific method to receive user selection directly on the Settings view.

How can we achieve the same flow with SwiftUI? I'm reading about @EnvironmentObject, is this a case where @EnvironmentObject would work? how would you implement the case described above with @EnvironmentObject?

Note: I've seen other similar questions but they were too specific for single cases. My question is broad and should generically apply to many differente cases.

Upvotes: 3

Views: 2087

Answers (1)

MatterGoal
MatterGoal

Reputation: 16430

I've found that a possible solution (instead of using @EnvironmentObject) would be to use @Binding.

For the Settings View I can have selectedColor and selectedCountry as @State

@State private var selectedColor:String = ""
@State private var selectedCountry:String = ""

Let's implement the Color Selection View. I can set a bind to a color variable this way:

@Binding var myColor:String = ""

Now if the value of myColor changes, since the variable is a Bind it will also change for the view that has the reference to this variable (in this case, the Settings view)

From the Settings view it would be enough to set the binding while presenting the color view.

NavigationLink(destination: ColorView(myColor: self.$selectedColor)) { 

In my opinion this would be a good way to substitute the Delegate logic.

Upvotes: 1

Related Questions