SWIFTUI:在视图中导航并返回

时间:2020-04-04 21:25:18

标签: swiftui swift5

我有一个关于迅速的问题。如何导航到视图?

现在,我的ContentView在有条件的(if)中显示launchScreen,Login或HomeView。

    var body: some View {

    VStack {

        if (sessionStore.session != nil) {

            UserProfileView(userProfile: self.profile ??  UserProfile(uid: "", firstName: "", lastName: "", birth: "", email: "", phone: ""))

        } else if show || UserDefaults.standard.bool(forKey: initialLaunchKey){

            AuthentificationView().transition(.move(edge: .bottom))

        } else {

            PageViewContainer( viewControllers: Page.getAll.map({  UIHostingController(rootView: PageView(page: $0) ) }), presentSignupView: { withAnimation { self.show = true }; UserDefaults.standard.set(true, forKey: self.initialLaunchKey) }).transition(.scale)
        }
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .background(Color.backgroundColor)
    .onTapGesture { UIApplication.shared.endEditing() }
}

但是,如果我在LoginView中,即使我在ContentView for HomeView中的情况变为真,我也不会进入HomeView ...

我通过可观察对象中的var进入视图(页面= 1,然后页面= 2 ...),我认为这不是更好的方法...

struct AuthentificationView: View {

    @EnvironmentObject var userSignup: UserSignup


    var body: some View {

        VStack {

            if (userSignup.page >= 1) {

                SignupView()
                    .transition(.asymmetric(insertion: .move(edge: .trailing), removal: .move(edge: .leading)))

            } else {

                LoginView()
                    .transition(.asymmetric(insertion: .move(edge: .leading), removal: .move(edge: .trailing)))

            }
        }
    }
}

谢谢

1 个答案:

答案 0 :(得分:0)

我无法测试您的代码(由于缺少自定义功能),因此仅凭经验尝试以下操作

  • 对每个带有过渡的视图使用显式条件
  • 使转场可动画化
  • 使容器保持过渡可动画化

像下面一样(抓痒)

var body: some View {

    VStack {

        if userSignup.page >= 1 {

            SignupView()
                .transition(AnyTransition.asymmetric(insertion: .move(edge: .trailing), 
                removal: .move(edge: .leading)).animation(.default))

        } 
        if userSignup.page == 0 {

            LoginView()
                .transition(AnyTransition.asymmetric(insertion: .move(edge: .leading), 
                removal: .move(edge: .trailing)).animation(.default))

        }
    }.animation(.default)
}