Unless I am missing something, wouldn't simply using a switch
trigger .onAppear
?
import SwiftUI
enum CustomTab: CaseIterable {
case one, two, three, four, five, six
}
struct CustomTabContainer: View {
//State values
@State private var selection: CustomTab = .one
//Body
var body: some View {
ZStack {
// Content area: only the active view is instantiated
Group {
switch selection {
case .one:
FirstCustomTabView()
case .two:
SecondCustomTabView()
case .three:
ThirdCustomTabView()
case .four:
FourthCustomTabView()
case .five:
FifthCustomTabView()
case .six:
SixthCustomTabView()
}
}
.foregroundStyle(.white)
.frame(maxWidth: .infinity, maxHeight: .infinity)
// Custom tab bar
HStack {
ForEach(CustomTab.allCases, id: \.self) { tab in
Button {
selection = tab
} label: {
Image(systemName: iconName(for: tab))
.font(.system(size: 24))
.frame(maxWidth: .infinity)
.foregroundStyle(selection == tab ? .accent : .gray)
}
}
}
.padding(20)
.background(.bar, in: Capsule())
.padding(20)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)
}
}
private func iconName(for tab: CustomTab) -> String {
switch tab {
case .one: return "1.circle.fill"
case .two: return "2.circle.fill"
case .three: return "3.circle.fill"
case .four: return "4.circle.fill"
case .five: return "5.circle.fill"
case .six: return "6.circle.fill"
}
}
}
struct FirstCustomTabView: View {
var body: some View {
ZStack {
Color.red
.ignoresSafeArea()
Text("First View")
.font(.largeTitle)
}
.onAppear {
print("first appeared")
}
}
}
struct SecondCustomTabView: View {
var body: some View {
ZStack {
Color.orange
.ignoresSafeArea()
Text("Second View")
.font(.largeTitle)
}
.onAppear {
print("second appeared")
}
}
}
struct ThirdCustomTabView: View {
var body: some View {
ZStack {
Color.yellow
.ignoresSafeArea()
Text("Third View")
.font(.largeTitle)
}
.onAppear {
print("third appeared")
}
}
}
struct FourthCustomTabView: View {
var body: some View {
ZStack {
Color.green
.ignoresSafeArea()
Text("Fourth View")
.font(.largeTitle)
}
.onAppear {
print("fourth appeared")
}
}
}
struct FifthCustomTabView: View {
var body: some View {
ZStack {
Color.blue
.ignoresSafeArea()
Text("Fifth View")
.font(.largeTitle)
}
.onAppear {
print("fifth appeared")
}
}
}
struct SixthCustomTabView: View {
var body: some View {
ZStack {
Color.purple
.ignoresSafeArea()
Text("Sixth View")
.font(.largeTitle)
}
.onAppear {
print("sixth appeared")
}
}
}
#Preview {
CustomTabContainer()
}