It’s day 82 of the 100 Days of SwiftUI! Yesterday, we learned about implementing notifications, creating custom context menus and more. Today, we’re focussing on building a tab bar and sharing data across tabs. Let’s dive in!
Building our tab bar in SwiftUI
This app is going to display four SwiftUI views inside a tab bar: one to show everyone that you met, one to show people you have contacted, another to show people you haven’t contacted, and a final one showing your personal information for others to scan.
Those first three views are variations on the same concept, but the last one is quite different. As a result, we can represent all our UI with just three views: one to display people, one to show our data, and one to bring all the others together using
Hacking with Swift, Paul Hudson (@twostraws)TabView
.
Sharing data across tabs using @EnvironmentObject
We’ve seen how we can share data across views. This is very useful, essential even, when building apps, as it allows us to keep re-using the same piece of data without making tons of objects. We can also share data across tabs, which is useful in the same way.
SwiftUI’s environment lets us share data in a really beautiful way: any view can send objects into the environment, then any child view can read those objects back out from the environment at a later date. Even better, if one view changes the object all other views automatically get updated – it’s an incredibly smart way to share data in larger applications.
In our app we have a
Hacking with Swift, Paul Hudson (@twostraws)TabView
that contains three instances ofProspectsView
, and we want all three of those to work as different views on the same shared data. This is a great example of where SwiftUI’s environment makes sense: we can define a class that stores one prospect, then place an array of those prospects into the environment so all our views can read it if needed.
Wrap up
That’s it for day 82! Tomorrow, we’ll look into QR codes and how to add and scan them with our app. Stay tuned for that!
100 Days of SwiftUI – Day 82