I am trying to create a a custom TabView for my app. I have followed a tutorial for this but I am unable to get the view to change depending on what button is pressed. My code is below for a button displayed on my TabView. When this is pressed, I want HomeView to show and when the Account button is pressed to show AccountView, etc.
I was wondering how I can get around this. I have tried using NavLinks but with no luck as I am unable to use the animation.
I am new to SwiftUI and trying to learn as I go.
Button{
withAnimation{
index = 0
}
}
label: {
HStack(spacing: 8){
Image(systemName: "house.fill")
.foregroundColor(index == 0 ? .white : Color.black.opacity(0.35))
.padding(10)
.background(index == 0 ? Color("BrightGreen") : Color.clear)
.cornerRadius(8)
Text(index == 0 ? "Home" : "")
.foregroundColor(.black)
}
}
You can use @State variable to decide which view should be shown to user. Then depending on what button is tapped set value of this variable. I've made really simple code to show the idea.
// Views to show
struct HomeView: View {
var body: some View {
Text("Home View")
}
}
struct AccountView: View {
var body: some View {
Text("Account View")
}
}
// Enum containing views available in tabbar
enum ViewToDisplay {
case home
case account
}
struct ContentView: View {
@State var currentView: ViewToDisplay = .home
var body: some View {
VStack {
switch currentView{
case .home:
HomeView()
case .account:
AccountView()
}
Spacer()
// Tabbar buttons
HStack {
Button(action: { currentView = .home }) { Text("Home") }
Button(action: { currentView = .account }) { Text("Account") }
}
}
}
}
It works like this: