我有登录的TextFields和密码的SecureField。当我的登录名和密码都正确时,如何进入另一个视图?
struct LoginBoard: View {
@State private var login = "Tony"
@State private var password = "1234"
var body: some View {
ZStack {
VStack {
HStack {
Text("Enter Login and Password")
}
HStack {
Image(systemName: "person")
TextField("Login", text: $login)
}
HStack {
SecureField("Password", text: $password)
}
Button("Login") {
}
}
}
}
}
在NavigationView{}中包装堆栈,并使用NavigationLink{}直接到另一个视图。示例代码如下:
import SwiftUI
struct LoginBoard: View {
@State private var login = "Tony"
@State private var password = "1234"
var body: some View {
NavigationView {
ZStack {
VStack {
HStack {
Text("Enter Login and Password")
}
HStack {
Image(systemName: "person")
TextField("Login", text: $login)
}
HStack {
SecureField("Password", text: $password)
}
NavigationLink {
WelcomeView()
} label: {
Text("Login")
.foregroundColor(.blue)
}
.disabled((login == "Tony" &&
password == "1234") ? false : true)
}
}
}
}
}
struct WelcomeView: View {
var body: some View {
Text("welcome!")
}
}
你应该使用NavigationView
,它相当于UIKit中的导航控制器并使用NavigationLink作为导航的segue或触发器。
struct LoginBoard: View {
@State private var login = "Tony"
@State private var password = "1234"
@State isLoginSuccess = false
var body: some View {
// like navigation controller
// that handles the navigation of views
NavigationView {
// DestinationView is the view will go
// to if credentials is correct
NavigationLink(destination: DestinationView(),
isActive: $isLoginSuccess) { }
ZStack {
VStack {
HStack {
Text("Enter Login and Password")
}
HStack {
Image(systemName: "person")
TextField("Login", text: $login)
}
HStack {
SecureField("Password", text: $password)
}
Button("Login") {
// if user and password are correct change
// isLoginSuccess to true and will navigate
// to the next View
isLoginSuccess = true
}
}
}
}
}
}