Search code examples
swiftswiftui

Programmatically navigate to new view in SwiftUI


Descriptive example:

login screen, user taps "Login" button, request is performed, UI shows waiting indicator, then after successful response I'd like to automatically navigate user to the next screen.

How can I achieve such automatic transition in SwiftUI?


Solution

  • 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<UserAuth,Never>()
    
      // required to conform to protocol 'ObservableObject' 
      let willChange = PassthroughSubject<UserAuth,Never>()
    
      func login() {
        // login request... on success:
        self.isLoggedin = true
      }
    
      var isLoggedin = false {
        didSet {
          didChange.send(self)
        }
    
        // willSet {
        //       willChange.send(self)
        // }
      }
    }