The SwiftUI @Environment property wrapper allows views to access shared data and respond to changes…
SwiftUI NavigationStack Tutorial: Building a Recipe App
Welcome to an exciting SwiftUI tutorial where we’ll create a recipe app! Using SwiftUI’s NavigationStack
, you’ll learn to navigate between a list of recipes and their detailed descriptions.
NavigationStack
in SwiftUI is used to create a stack of views where the user can navigate between different screens. It works like a stack of cards where each new view is placed on top of the others. You can navigate to new views using NavigationLink
, and each link can be associated with specific data.The stack shows the top view and allows navigation back to previous views. NavigationStack
can be managed automatically or with custom state management to control the navigation flow programmatically. For diverse navigation needs, it can handle multiple view types by matching navigation links with destinations based on data types.
-
- Define Your Recipe Model:
struct Recipe: Identifiable, Hashable { var id = UUID() var title: String }
- Create the Recipe Detail View:
struct RecipeDetailView: View { var recipe: Recipe var body: some View { Text(recipe.title) } }
- Set Up the NavigationStack:
struct ContentView: View { var recipes = [Recipe(title: "Lasagna"), Recipe(title: "Tiramisu"), Recipe(title: "Pizza")] var body: some View { NavigationStack { List(recipes) { recipe in NavigationLink(recipe.title, value: recipe) } .navigationDestination(for: Recipe.self) { recipe in RecipeDetailView(recipe: recipe) } } } }
- Define Your Recipe Model:
Conclusion:
-
-
- You’ve just created a SwiftUI app featuring a list of recipes with navigable details. This tutorial showcases the power and simplicity of using
NavigationStack
in SwiftUI app development. -