在 NavigationLink 中打开新视图并关闭当前视图

问题描述 投票:0回答:1

这是 Login() 视图:

struct Login: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View{
        
        VStack{
            
            HStack{
                                    
                Button(action: {
                    
                    presentationMode.wrappedValue.dismiss()

                }) {
                    Image(systemName: "xmark")
                        .resizable()
                        .frame(width: 18, height: 18)
                }

            }
            
            
            NavigationLink(destination: CreateAccount().navigationBarBackButtonHidden(true), label: {
                Text("create account")
                
                // and close the current view Login()
            })                
        }       
    }
}

是否可以打开一个新视图,在本例中为 CreateAccount() 并关闭当前视图 Login()?

swiftui swiftui-navigationlink swiftui-navigationview
1个回答
1
投票

为了做到这一点,我建议完全跳过

NavigationView
,请参阅 here 了解更多信息。您的情况的示例:

//You need an `ObservedObject` to do this, and a overall holder view

enum ViewStates{
//Declare possible views
case ContentView
case Login
case CreateAccount

}

//Then use an observableObject

class viewControl: ObservableObject{
@Published var currentView: ViewStates = .ContentView
}

//Finally, pass this into your views. Take a look at the second part of the tutorial I posted below for more info
//such as using `EnvironmentObject` and adding animation. Example implimentation below:


struct ControllerView: View{
@StateObject var controller: viewControl

var body: some View{
switch controller.currentView{
case .ContentView:
ContentView(controller: controller)
case .Login:
Login(controller: controller)
case .CreateAccount:
CreateAccount(controller: controller)
}
}

}

接下来,您的所有视图中都需要有

@ObservedObject var controller: viewControl
。请注意,您不需要在 switch 子句中使用默认语句,因为
enum
声明了所有可能的值。以下是 CreateAccount 视图的示例。您也不再需要解雇 - 事实上,这将不再起作用。

struct CreateAccount: View{
@ObservedObject var controller: viewControl

var body: some View{
//Content
Button("Dismiss"){
controller.currentView = .ContentView
}
}

}

这将允许您通过单击来切换视图。不要在 ContentView 中使用 NavigationLink,而是执行以下操作:

Button{
controller.currentView = .CreateAccount
} label: {
Text("Create Account")
}

要返回,您只需再次设置该值即可。这也可以扩展以显示更多视图。

教程第二部分

© www.soinside.com 2019 - 2024. All rights reserved.