Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list an array of TabView items in SwiftUI?

I have a project where parts of ContentView is supposed to change when different tabs are selected. I have the following struct and the array for the TabView items:

struct TabItem: Identifiable {
    var id = UUID()
    var title: Text
    var image: Image
    var tag: Int
}

let tabData = [
    TabItem(title: Text("Tab 1"), image: Image(systemName: "1"), tag: 1),
    TabItem(title: Text("Tab 2"), image: Image(systemName: "2"), tag: 2),
    TabItem(title: Text("Tab 3"), image: Image(systemName: "3"), tag: 3),
    TabItem(title: Text("Tab 4"), image: Image(systemName: "4"), tag: 4)
]

I am trying to list these inside TabView but couldn't figure out how to do so. Tried below approach, but having no luck so far.

TabView {
    ContentView()
        .tabItem {
        // code goes here...
        }.tag // tag goes here
}

I am aware that I can also use the TabView(selection: ) with an @State variable, but I am also not sure how to implement that.

Thank you!

like image 565
fankibiber Avatar asked Nov 16 '19 13:11

fankibiber


1 Answers

TabView can be displayed as below (attribute selectedTab keeps track of the tab that is selected by the user) :

import SwiftUI

struct ContentView: View {
    let tabData = [
        TabItem(title: Text("Tab 1"), image: Image(systemName: "1"), tag: 1),
        TabItem(title: Text("Tab 2"), image: Image(systemName: "2"), tag: 2),
        TabItem(title: Text("Tab 3"), image: Image(systemName: "3"), tag: 3),
        TabItem(title: Text("Tab 4"), image: Image(systemName: "4"), tag: 4)
    ]

    @State private var selectedTab = 0

    var body: some View {

        TabView(selection: $selectedTab) {

            ForEach(tabData) { tabItem in
                Text("Screen: \(tabItem.tag)")
                    .tabItem {
                        tabItem.title
                        tabItem.image
                }.tag(tabItem.tag)
            }
        }

    }
}

struct TabItem: Identifiable {
    var id = UUID()
    var title: Text
    var image: Image
    var tag: Int
}
like image 157
Partha G Avatar answered Sep 24 '22 11:09

Partha G