首页 > 解决方案 > 如何使用 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()
            }
        }
    }
}

谢谢!

标签: iosswiftswiftui

解决方案


重新安排你的观点,这样

而不是直接进入你的登录视图,有一个像这样的中间视图:

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

推荐阅读