Programmatically navigate to new view in SwiftUI

后端 未结 6 512
梦如初夏
梦如初夏 2020-12-01 20:52

Descriptive example:

login screen, user taps \"Login\" button, request is performed, UI shows waiting indicator, then after successful response I\'d like to automati

6条回答
  •  天涯浪人
    2020-12-01 21:49

    struct LoginView: View {
        
        @State var isActive = false
        @State var attemptingLogin = false
        
        var body: some View {
            ZStack {
                NavigationLink(destination: HomePage(), isActive: $isActive) {
                    Button(action: {
                        attlempinglogin = true
                        // Your login function will most likely have a closure in 
                        // which you change the state of isActive to true in order 
                        // to trigger a transition
                        loginFunction() { response in
                            if response == .success {
                                self.isActive = true
                            } else {
                                self.attemptingLogin = false
                            }
                        }
                    }) {
                        Text("login")
                    }
                }
                
                WaitingIndicator()
                    .opacity(attemptingLogin ? 1.0 : 0.0)
            }
        }
    }
    

    Use Navigation link with the $isActive binding variable

提交回复
热议问题