Home > Software engineering >  How to navigate to specific page in tab view using ForEach in SwiftUI?
How to navigate to specific page in tab view using ForEach in SwiftUI?

Time:11-08

I want to create some simple navigation, where when I press on a button from a list, I am taken to a specific page on a page style tab view.

My code is below:

struct NavView: View {
    var body: some View {
        NavigationView {
            List {
                NavigationLink(destination: PageView(tag: 0)) {
                    Text("0")
                }
                NavigationLink(destination: PageView(tag: 1)) {
                    Text("1")
                }
                NavigationLink(destination: PageView(tag: 2)) {
                    Text("2")
                }
                NavigationLink(destination: PageView(tag: 3)) {
                    Text("3")
                }
                NavigationLink(destination: PageView(tag: 4)) {
                    Text("4")
                }
            }
        }
        .tabViewStyle(.page(indexDisplayMode: .never))
    }
}

struct PageView: View {
    
    var tag: Int
    
    var body: some View {
        TabView {
            ForEach(0..<5, id: \.self) { i in
                Text("\(i)")
            }
        }
        .tabViewStyle(.page(indexDisplayMode: .never))
    }
}

As an example, if I wanted to go to the page labeled 3, I would like to use the click on the list option labeled 3 on the NavView to direct me to that page on PageView, which is being created with a ForEach. How would I be able to accomplish this? I hope my request made sense.

CodePudding user response:

You can use the selection binding of TabView like this.

struct NavView: View {
    
    var body: some View {
        NavigationView {
            List {
                ForEach(0..<5, id: \.self) { i in
                    NavigationLink(destination: PageView(tag: i)) {
                        Text("\(i)")
                    }
                }
            }
        }
    }
}


struct PageView: View {
    
    @State var tag: Int = 0
    
    var body: some View {
        TabView(selection: $tag) {
            ForEach(0..<5, id: \.self) { i in
                Text("\(i)")
                    .tag(i)
            }
        }
        .tabViewStyle(.page(indexDisplayMode: .never))
    }
}
  • Related