[英]Present new SwiftUI view on button press
我想在我的應用程序上有一個使用 SwiftUI 的登錄表單。 我有兩個按鈕:登錄和注冊。 我希望能夠按下注冊按鈕並讓我制作的新 SwiftUI 視圖出現/替換另一個視圖。 這是我的按鈕代碼:
let signupButton = Color(red: 103.0/255.0, green: 104.0/255.0, blue: 255.0/255.0)
let text : String
var body: some View {
Button(action: {
}) {
Text(text)
.accentColor(.white)
// .frame(minWidth: 0, maxWidth: 300)
.frame(width: 200)
.padding()
.background(signupButton)
.cornerRadius(10)
.padding()
}
}
}
然后對於我的登錄頁面:
struct LoginPage: View {
let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
let textFieldBackground = Color(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0)
let textFieldBorder = Color(red: 112.0/255.0, green: 112.0/255.0, blue: 112.0/255.0)
let signupButton = Color(red: 103.0/255.0, green: 104.0/255.0, blue: 255.0/255.0)
var body: some View {
NavigationView {
Text("Don't have an account?")
.fontWeight(.light)
NavigationLink(destination: SignupPage()) {
ActionButton(text: "sign up")
}
}
.navigationBarTitle(Text("Signin")
.foregroundColor(Color.black))
}
}
}
問題是,當我按下按鈕時,未顯示注冊頁面。 我有一個名為SignupPage()
的已經設計SignupPage()
頁面,參考是正確的。 我不知道這是否是一個錯誤,或者我是否只是做錯了這一切
NavigationLink
已經作為一個按鈕,你不需要使用Button
。 如果你這樣做了,你需要為它定義一個動作。 這是一個修復:
struct LoginPage: View {
let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
let textFieldBackground = Color(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0)
let textFieldBorder = Color(red: 112.0/255.0, green: 112.0/255.0, blue: 112.0/255.0)
let signupButton = Color(red: 103.0/255.0, green: 104.0/255.0, blue: 255.0/255.0)
var body: some View {
NavigationView {
VStack {
Text("Don't have an account?")
.fontWeight(.light)
NavigationLink(destination: SignupPage()) {
ActionButton(text: "sign up")
}
}
}
.navigationBarTitle(Text("Signin")
.foregroundColor(Color.black))
}
}
struct SignupPage: View {
var body: some View {
Text("Signup page placeholder")
}
}
struct ActionButton: View {
let signupButton = Color(red: 103.0/255.0, green: 104.0/255.0, blue: 255.0/255.0)
let text : String
var body: some View {
Text(text)
.accentColor(.white)
// .frame(minWidth: 0, maxWidth: 300)
.frame(width: 200)
.padding()
.background(signupButton)
.cornerRadius(10)
.padding()
}
}
如果您需要使用按鈕並在導航到另一個視圖之前有某種行為,您可以使用以下代碼:
struct FooView: View {
@State private var presentView = false
var body: some View {
NavigationLink(destination: AnotherView(), isActive: self.$presentView) {
Button(action: {
//do something here
self.presentView = true
}) {
Text("Navigate!")
.frame(width: 100, height: 200)
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.