[英]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.