Programmatically navigate to new view in SwiftUI

后端 未结 6 509
梦如初夏
梦如初夏 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:47

    You can replace the next view with your login view after a successful login. For example:

    struct LoginView: View {
        var body: some View {
            ...
        }
    }
    
    struct NextView: View {
        var body: some View {
            ...
        }
    }
    
    // Your starting view
    struct ContentView: View {
    
        @EnvironmentObject var userAuth: UserAuth 
    
        var body: some View {
            if !userAuth.isLoggedin {
                LoginView()
            } else {
                NextView()
            }
    
        }
    }
    

    You should handle your login process in your data model and use bindings such as @EnvironmentObject to pass isLoggedin to your view.

    Note: In Xcode Version 11.0 beta 4, to conform to protocol 'BindableObject' the willChange property has to be added

    import Combine
    
    class UserAuth: ObservableObject {
    
      let didChange = PassthroughSubject()
    
      // required to conform to protocol 'ObservableObject' 
      let willChange = PassthroughSubject()
    
      func login() {
        // login request... on success:
        self.isLoggedin = true
      }
    
      var isLoggedin = false {
        didSet {
          didChange.send(self)
        }
    
        // willSet {
        //       willChange.send(self)
        // }
      }
    }
    

提交回复
热议问题