Push View programmatically in callback, SwiftUI

后端 未结 5 1608
长发绾君心
长发绾君心 2020-12-17 09:25

It seems to me that Apple is encouraging us to give up using UIViewController in SwiftUI, but without using view controlelrs, I feel a little bit powerless. Wha

5条回答
  •  执笔经年
    2020-12-17 10:00

    as @Bhodan mentioned you can do it by changing state

    Using EnvironmentObject with SwiftUI

    1. Add UserData ObservableObject :
    class UserData: ObservableObject, Identifiable {
    
        let id = UUID()
        @Published var firebase_uid: String = ""
        @Published var name: String = ""
        @Published var email: String = ""
        @Published var loggedIn: Bool = false
    }
    

    the loggedIn property will be used to monitor when a change in user logs in or out

    1. Now add it as an @EnvironmentObject in your SceneDelegate.swift file in Xcode this just makes it so its accessible everywhere in your app
    class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    
        var window: UIWindow?
    
    
        func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
            // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
            // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
            // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
    
            // Create the SwiftUI view that provides the window contents.
            let userData = UserData()
            let contentView = ContentView().environmentObject(userData)
    
            // Use a UIHostingController as window root view controller.
            if let windowScene = scene as? UIWindowScene {
                let window = UIWindow(windowScene: windowScene)
                window.rootViewController = UIHostingController(rootView: contentView)
                self.window = window
                window.makeKeyAndVisible()
            }
        }
    

    Once you make any change to the loggedIn property any UI that is Binded to it will respond to the true/false value change

    the as @Bhodan mentioned just add this to your view and it will respond to that change

    
    struct LoginView: View {
    @EnvironmentObject var userData: UserData
    
    var body: some View {
    NavigationView {
    VStack {
    NavigationLink(destination: ProfileView(), isActive: self.$userData.loggedin) {
        EmptyView()
        }.hidden()
       }
      }
     }
    }
    

提交回复
热议问题