SWIFTUI 按钮登录身份验证并转到新视图 [英] SWIFTUI button login authentication and go to new View
问题描述
输入电子邮件和密码后,我需要轻松验证文本字段,下一步按钮,检查电子邮件和密码并转到下一个视图.它是如何制作的?我有一些代码状态变量和按钮:
I ned easy validation TextField after enter Email and password, next step push button, check Email and Password and go to next View. How it make? I have a some code State var and Button:
struct ContentView: View {
@State var email = "1"
@State var password = "1"
Button(action: {
if self.email == "1" && self.password == "1"{
print("Button tapped")
NextMyView()
}else {
print("error")
}
}) {
Image(systemName: "heart.fill")
.foregroundColor(.red)
}
但我的想法行不通,我如何进行此验证并在按下按钮后转到下一个视图.
But my idea dos not work, how I can make this validation and after push button go to next View.
推荐答案
您将需要 NavigationView
和 NavigationLink
实现您的目标.
You will need NavigationView
and a NavigationLink
to achieve what you're looking for.
NavigationView
会将所有内部视图包装在一个导航控制器中,而 NavigationLink
就像一个触发导航的特殊按钮.
NavigationView
will wrap all the inner views within a navigation controller, and NavigationLink
is like a special button that triggers the navigation.
struct ContentView: View {
@State private var email: String = "root"
@State private var password: String = "toor"
@State private var isLoginValid: Bool = false
@State private var shouldShowLoginAlert: Bool = false
var body: some View {
NavigationView {
VStack(alignment: .center) {
TextField("email", text: self.$email)
TextField("password", text: self.$password)
NavigationLink(destination: Text("Success"),
isActive: self.$isLoginValid) {
/*
Here we put the content view of `NavigationLink`.
It could be any `View` even `Button` but in this
example we use a `Text` with `onTapGesture`.
*/
Text("Login")
.onTapGesture {
//determine login validity
let isLoginValid = self.email == "root" && self.password == "toor"
//trigger logic
if isLoginValid {
self.isLoginValid = true //trigger NavigationLink
}
else {
self.shouldShowLoginAlert = true //trigger Alert
}
}
}
}
.navigationBarTitle("Login Screen")
.alert(isPresented: $shouldShowLoginAlert) {
Alert(title: Text("Email/Password incorrect"))
}
}
}
}
NavigationLink
定义:
destination
导航到一个简单的Text
视图- 在您的情况下,您应该将其更改为
NextMyView()
- 在您的情况下,您应该将其更改为
destination
which navigates to a simpleText
view- In your case you should change it to
NextMyView()
- In your case you should change it to
- 在您的情况下,您可以将
Text
更改为Image(systemName: "heart.fill")
PS:作为额外的内容,我包含了触发和显示登录失败警报的逻辑.
希望它有帮助:)
PS: As an extra, I included the logic to trigger and show an alert on login failure.
Hope it helps :)
这篇关于SWIFTUI 按钮登录身份验证并转到新视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!