Go to a new view using SwiftUI

前端 未结 12 1882
走了就别回头了
走了就别回头了 2020-12-08 19:28

I\'ve got a basic view with a button using SwiftUI and I\'m trying to present a new screen/view when the button is tapped. How do I do this? Am I suppose to create a delegat

12条回答
  •  长情又很酷
    2020-12-08 20:25

    I made a ViewModifier for this. It also means that there is no navigation bar. You can call it like so:

    .navigate(to: MainPageView(), when: $willMoveToNextScreen)
    

    This can be attached to anything, so I typically attach it to the end of the body, for example:

    @State private var willMoveToNextScreen = false
    
    var body: some View {
        VStack {
            /* ... */
        }
        .navigate(to: MainPageView(), when: $willMoveToNextScreen)
    }
    

    Code (remember to import SwiftUI):

    extension View {
    
        /// Navigate to a new view.
        /// - Parameters:
        ///   - view: View to navigate to.
        ///   - binding: Only navigates when this condition is `true`.
        func navigate(to view: NewView, when binding: Binding) -> some View {
            NavigationView {
                ZStack {
                    self
                        .navigationBarTitle("")
                        .navigationBarHidden(true)
    
                    NavigationLink(
                        destination: view
                            .navigationBarTitle("")
                            .navigationBarHidden(true),
                        isActive: binding
                    ) {
                        EmptyView()
                    }
                }
            }
        }
    }
    

提交回复
热议问题