
Here’s a basic SwiftUI app demonstrating navigation from a list of items to a detail view, along with explanations:
Data Model (Item Struct):
- Defines a structure to represent each item in the list.
id
: A unique identifier (UUID) for each item.name
: The name of the item displayed in the list.details
: The detailed information about the item shown in the detail view.
ItemDetailView:
- Takes an
Item
object as input. - Displays the item’s
name
anddetails
in aVStack
. - Sets the navigation bar title to the item’s name.
ContentView:
items
array holds sample item data. Replace this with your actual items.NavigationView
provides the navigation structure (back button, navigation bar).List
creates a scrollable list of items.NavigationLink
wraps each item:destination
: Specifies the view to navigate to (ItemDetailView
) when the item is tapped.- The content of the
NavigationLink
is theText
view displaying the item’s name in the list.
import SwiftUI
// Data Model
struct Item: Identifiable {
let id = UUID()
let name: String
let details: String
}
// Detail View
struct ItemDetailView: View {
let item: Item
var body: some View {
VStack(alignment: .leading) {
Text(item.name)
.font(.title)
Text(item.details)
.padding(.top, 10)
}
.padding()
.navigationTitle(item.name)
}
}
// Main View
struct ContentView: View {
let items: [Item] = [
Item(name: "Item 1", details: "Details for item 1 go here."),
Item(name: "Item 2", details: "Details for item 2 are more detailed."),
Item(name: "Item 3", details: "And here's the description for item 3.")
]
var body: some View {
NavigationView {
List(items) { item in
NavigationLink(destination: ItemDetailView(item: item)) {
Text(item.name)
}
}
.navigationTitle("Items")
}
}
}
How it Works:
- The
ContentView
displays a list of items. - When the user taps an item, the
NavigationLink
triggers navigation to theItemDetailView
. - The
ItemDetailView
receives the selecteditem
and displays its details. - The user can use the back button in the navigation bar to return to the list view.
Key Points:
- Navigation: Uses
NavigationView
andNavigationLink
for basic navigation. - List View: Employs
List
to efficiently display a collection of items. - Data Model: The
Item
struct models your data with an identifier and properties to display. - Customizable: Easily adapt the
Item
struct and the views to fit your specific data and design requirements. - Scalable: This pattern can be extended to handle more complex lists and detail views.