Updated for Xcode 12.5
SwiftUI’s NavigationLink
can be used inside list rows to present new views when a row is tapped. If the NavigationLink
wraps around your entire row, the system automatically understands to make the entire row tappable in order to present the new view.
To demonstrate this, the following code creates a PlayerView
that is able to show one selected football player’s name in large text. It then creates a List
for several players, where each row in the list has a NavigationLink
that passes in the name of the player that was tapped:
struct PlayerView: View {
let name: String
var body: some View {
Text("Selected player: \(name)")
.font(.largeTitle)
}
}
struct ContentView: View {
let players = [
"Roy Kent",
"Richard Montlaur",
"Dani Rojas",
"Jamie Tartt",
]
var body: some View {
NavigationView {
List(players, id: \.self) { player in
NavigationLink(destination: PlayerView(name: player)) {
Text(player)
}
}
.navigationTitle("Select a player")
}
}
}
Notice how we have literally put a list row inside a navigation link – SwiftUI makes it work thanks to its remarkable composition abilities.
SPONSORED Check out Stream's cross-platform open source chat SDK on GitHub! Write once and deploy your app with fully featured chat UI on iOS and macOS.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.