ios – Programmatically select item from list


I have a list with NavigationLinks in it. I wish to programmatically select/tap an item from the list. I tried using NavigationLink(tag…, selection…) API, but looks like it’s deprecated from iOS 16.

Code:

import SwiftUI
import Foundation

struct BookItem {
    let id: Int
    let name: String
    
    init(id: Int, name: String) {
        self.id = id
        self.name = name
    }
}

struct ContentView: View {
    let bookList: [BookItem] = [BookItem.init(id: 0, name: "History"), BookItem.init(id: 1, name: "Math"), BookItem.init(id: 2, name: "Science")]

    let selectBookItemId: Int = 1
    
    var body: some View {
        NavigationStack {
            VStack {
                List(bookList, id: \.name) { bookItem in
                    NavigationLink(destination: { DetailsView(bookItem: bookItem) },
                    label: {
                        HStack {
                            Text(bookItem.name)
                            Spacer()
                        }
                        .contentShape(Rectangle())
                    })
     
                    // NOTE: Was going to use this, but it is deprecated
//                    NavigationLink(
//                        destination: ,
//                        tag:,
//                        selection:,
//                        label: {})
                }
            }
        }
    }
}

struct DetailsView: View {
    var bookItem: BookItem

    var body: some View {
        VStack {
            Text(bookItem.name).font(.body.bold()).foregroundColor(Color.blue)
        }
    }
}

In my sample code above, let’s say I wish to programmatically select 2nd item from the list i.e. when I execute the code, it should show me DetailsView with “Math” written on it.

How can it be achieved now since NavigationLink API is deprecated?

Thanks!

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img