ios - 如何使用 SwiftUI 中的按钮在视图之间导航?
问题描述
我在登录页面中,当我按下登录按钮时,如果登录完成且没有错误,我想导航到新视图,如果登录失败,我想留在同一个视图上。这是我的代码:
struct LogIn: View {
@State var mesaj = ""
@State private var email = ""
@State private var password = ""
@EnvironmentObject var model: Model
var body: some View {
NavigationView {
VStack {
// EMAIL
TextField("E-mail", text: $email).textFieldStyle(RoundedBorderTextFieldStyle())
// PASSWORD
TextField("Password", text: $password).textFieldStyle(RoundedBorderTextFieldStyle())
// this is the login button
Button(action: {
loginRequest(link: "https://someapi.com", email: self.email, password: self.password) // this is the login request
let seconds = 5.0
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
self.mesaj = message
if message == "You are now logged in"
{
// here I want to navigate to a new view
}
}
}) {
Text("LogIn")
}
Text(mesaj)
Spacer()
}
}
}
}
谢谢!
解决方案
重新安排你的观点,这样
而不是直接进入你的登录视图,有一个像这样的中间视图:
struct PreLogIn: View {
@State var loggedInSuccess = false // that you pass into the LogIn() view
// or
@EnvironmentObject var model: Model // with a @Published var loggedInSuccess = false
var body: some View {
Group {
if model.loggedInSuccess {
YourNextView()
}
else {
LogIn()
}
}
}
}
然后在您的 LogIn() 视图按钮操作中:
model.loggedInSuccess = true
推荐阅读
- bixby - 如何摆脱所有“警告 this.name 可能为空”的警告?
- java - 如何在 Spring Boot 应用程序中将参数传递给自定义 JSON 反序列化器
- php - 在 Laravel 中显示 Eloquent 关系
- php - 我正在从数据库中搜索。结果它为一家酒店带来了 3 间客房。这在我的 android recyclerview 中显示为 3 家酒店
- html - 我怎样才能使幻灯片上的箭头居中?在两者之间留下a100px的距离并保持在不同宽度的同一个地方
- python - 编码和脚本有什么区别?
- wordpress - 更改主机后如何从 Google Drive 自动更新 WordPress 网站上的链接?
- python - 如何从 Matlab 正确调用 GEKKO
- sql - SQL 用下划线分割名字
- http - Nagios 警报返回“NRPE:无法读取输出”命令:check_service!httpd