My code currently shows two buttons next to each other, one button being countries and the other being states. I want to make it so that once a button is pressed, a new set of buttons will appear. For example, if countries is pressed, the two new buttons will be America and Canada. If states is pressed, the two new buttons will be California and Nevada. Ultimately I would like to make a long chain of questions where each button pressed determines the next question and options.
My current code is this
import SwiftUI
struct ContentView: View {
@StateObject var triviaManager = TriviaManager()
var body: some View {
NavigationView {
VStack(spacing: 40) {
VStack(spacing: 20) {
Text("Foodie's Pick")
.lilacTitle()
Text("Let's Find your Match")
.foregroundColor(Color("AccentColor"))
}
HStack { NavigationLink {
TriviaView()
.environmentObject(triviaManager)
} label: {
PrimaryButton(text: "Countries")
}
NavigationLink {
TriviaView()
.environmentObject(triviaManager)
} label: {
PrimaryButton(text: "States")
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.edgesIgnoringSafeArea(.all)
.background(Color(red: 1, green: 1, blue: 1))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
and this code visually looks like this
CodePudding user response:
You can use either if else{} or switch or NavigationLink to achieve this.
In the below sample, I used if else{} with a Bool variable to determine which buttons to show next. Also, this kind of process will show the buttons in the same view, so it may be cleaner than Navigating back and forth to next buttons.
import SwiftUI
struct ContentView: View {
@State var isCountry = false
@State var isState = false
var body: some View {
VStack {
ZStack {
if !isCountry && !isState {
HStack {
Button {
isCountry.toggle()
} label: {
Text("Countries")
}
Button {
isState.toggle()
} label: {
Text("States")
}
}
}
else if isCountry {
HStack {
Button {
} label: {
Text("America")
}
Button {
} label: {
Text("Canada")
}
}
}
else if isState {
HStack {
Button {
} label: {
Text("California")
}
Button {
} label: {
Text("Nevada")
}
}
}
}
}
}
}