SwiftUI Change View with Button

前端 未结 4 1866
失恋的感觉
失恋的感觉 2021-02-04 18:48

I understand there is PresentationButton and NavigationButton in order to change views in the latest SwiftUI. However I want to do a simple operation like below. When user click

4条回答
  •  情深已故
    2021-02-04 18:56

    I had the same need in one of my app and I've found a solution...

    Basically you need to insert your main view in a NavigationView, then add an invisible NavigationLink in you view, create a @state var that controls when you want to push the view and change it's value on your login callback...

    That's the code:

    struct ContentView: View {
        @State var showView = false
        var body: some View {
            NavigationView {
                VStack {
                    Button(action: {
                        print("*** Login in progress... ***")
                        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                            self.showView = true
                        }
                    }) {
                        Text("Push me and go on")
                    }
    
                    //MARK: - NAVIGATION LINKS
                    NavigationLink(destination: PushedView(), isActive: $showView) {
                        EmptyView()
                    }
                }
            }
        }
    }
    
    
    struct PushedView: View {
        var body: some View {
            Text("This is your pushed view...")
                .font(.largeTitle)
                .fontWeight(.heavy)
        }
    }
    

提交回复
热议问题