【问题标题】:How do I navigate between views using a button in SwiftUI?如何使用 SwiftUI 中的按钮在视图之间导航?
【发布时间】:2020-03-19 07:46:24
【问题描述】:

我在登录页面中,当我按下登录按钮时,如果登录没有错误完成,我想导航到新视图,如果登录失败,我想留在同一个视图上。这是我的代码:

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()
            }
        }
    }
}

谢谢!

【问题讨论】:

标签: ios swift swiftui


【解决方案1】:

重新排列你的观点,这样

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    相关资源
    最近更新 更多