iOS SwiftUI - NavigationLink打开新视图并关闭当前视图



这是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()?

为了做到这一点,我建议完全跳过NavigationView,请参阅此处了解更多信息。举个例子:

//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")
}

要返回,只需重新设置值。还可以展开以显示更多视图。

教程第二部分

相关内容

  • 没有找到相关文章

最新更新