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!
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With