[英]How do I make buttons lead to other buttons in SwiftUI?
我的代碼目前顯示兩個相鄰的按鈕,一個按鈕是國家,另一個是州。 我想讓它一旦按下一個按鈕,就會出現一組新的按鈕。 例如,如果按下國家/地區,則兩個新按鈕將是美國和加拿大。 如果按下州,兩個新按鈕將是加利福尼亞和內華達。 最后,我想提出一長串問題,按下每個按鈕都會決定下一個問題和選項。
我目前的代碼是這樣的
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()
}
}
這段代碼看起來像這樣
您可以使用 if else{} 或 switch 或 NavigationLink 來實現此目的。
在下面的示例中,我使用帶有 Bool 變量的 if else{} 來確定接下來要顯示的按鈕。 此外,這種過程將在同一視圖中顯示按鈕,因此它可能比來回導航到下一個按鈕更清晰。
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.