LAST CHANCE: Save 50% on all my Swift books and bundles! >>

How to push a new view when a list row is tapped

Paul Hudson    @twostraws   

Updated for Xcode 13.0

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")
        }
    }
}

Download this as an Xcode project

Notice how we have literally put a list row inside a navigation link – SwiftUI makes it work thanks to its remarkable composition abilities.

Click here to save 50% on all my books and bundles!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.6/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.