[英]How do I make buttons lead to other buttons in SwiftUI?
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()
}
}
You can use either if else{} or switch or NavigationLink to achieve this.您可以使用 if else{} 或 switch 或 NavigationLink 来实现此目的。
In the below sample, I used if else{} with a Bool variable to determine which buttons to show next.在下面的示例中,我使用带有 Bool 变量的 if else{} 来确定接下来要显示的按钮。 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")
}
}
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.