0

In my SwiftUI/iOS 15+ app I would like to allow the user to navigate from a List to a side-scrolling TabView, such that tapping the Nth item in the List navigates directly to the Nth page in the TabView. (From there, the user can swipe left/right to side-scroll through the other items.)

I have this code which almost works:

import SwiftUI

struct Thing: Identifiable {
    var id = UUID()
    var name: String
    var detail: String
}

struct ContentView: View {
    let things = [
        Thing(name: "apple", detail: "A kind of fruit."),
        Thing(name: "Chevy", detail: "A make of automobile."),
        Thing(name: "1984", detail: "A novel by George Orwell."),
        Thing(name: "USA", detail: "A sovereign nation."),
        Thing(name: "baseball", detail: "A team sport."),
    ]

    var body: some View {
        NavigationView {
            List(self.things) { thing in
                NavigationLink(destination: {
                    TabView { //How to display selected item?
                        ForEach(self.things) { thing in
                            Text("\(thing.name): \(thing.detail)")
                                .tag(thing.name)
                        } //ForEach
                    } //TabView
                    .tabViewStyle(.page(indexDisplayMode: .always))
                }) {
                    Text(thing.name)
                } //NavigationLink
            } //List
        } //NavigationView
    } //body
}

The problem is that clicking any item in the List always navigates to the first page of the TabView. I don't know how to specify an initial "selection:" for the TabView, based on the tag (or index?) of the item tapped in the List. Is there a way to solve this without resorting to UIKit?

protasm
  • 1,209
  • 12
  • 20

0 Answers0