我试图使用以下代码弹出到根视图控制器:
self.navigationController!.popToRootViewController(animated: true)
通常这个代码是有效的,但当当前视图是一个模态时尝试使用这个代码会出现错误。在这种情况下,我该如何返回到根视图控制器?
谢谢你提前。
您可以检查当前控制器是否显示,如果已显示,则将其取消并转到rootViewController
,否则直接转到rootViewController
if self.presentingViewController != nil {
self.dismiss(animated: false, completion: {
self.navigationController!.popToRootViewController(animated: true)
})
}
else {
self.navigationController!.popToRootViewController(animated: true)
}
self.navigationController!.popToRootViewController(animated:true)
不正确?你应该使用 presentingViewController
的导航控制器来弹出到根视图控制器,才能更加准确。 - Yuchen假设您的模态视图有以下 ViewController 相关联。
基本上,要隐藏显示为模态视图 的您的视图,您可以使用来自 ViewController 实例的 dismiss(animated: Bool)
方法。
而对于作为推入视图显示的视图,例如,您可以从 navigationController 属性中使用这些方法:popToRootViewController(animated: Bool)
、popViewController(animated:Bool)
class ModalViewController: UIViewController {
@IBAction func backButtonTouched(_ sender: AnyObject) {
let navigationController = self.presentingViewController as? UINavigationController
self.dismiss(animated: true) {
let _ = navigationController?.popToRootViewController(animated: true)
}
}
}
self.dismiss(animated: true, completion: nil)
CATransaction.begin()
CATransaction.setCompletionBlock {
self.dismiss(animated: true, completion: nil)
}
self.navigationController?.popViewController(animated: false)
CATransaction.commit()
参考自: 弹出视图控制器的完成块
以上内容适用于弹出单个视图控制器。如果您需要弹出多个视图控制器,popToRootViewController
将无法工作(由于动画存在不平衡的调用)。
在这种情况下,请使用以下(手动)方法来删除它们:
guard let navigationController = self.navigationController else { return }
var navigationViewControllers = navigationController.viewControllers
navigationViewControllers.removeLast(navigationViewControllers.count - 1)
self.navigationController?.viewControllers = navigationViewControllers
使用通知怎么样?
你的模态视图只需发布通知
然后你的导航控制器接收到通知,就可以弹回根视图控制器了。
[(UINavigationController *)self.presentingViewController popToRootViewControllerAnimated:NO];
[self dismissViewControllerAnimated:YES completion:nil];
参考答案请查看此处:
这里是我的示例视图,展示它如何工作。
struct ContentView: View {
@EnvironmentObject private var globalObj: GlobalClass
var body: some View {
CustomNavView{
VStack{
RootCustomNavLink(destination: FirstView()
.customNavigationTitle("Custom View").customNavigationBarReturnButtonHidden(true), label: {
Text("Navigate View One").buttonStyleBlue()
})
}.customNavigationTitle("Home")
.customNavigationBarBackButtonHidden(true)
.customNavigationBarReturnButtonHidden(true)
}
}
}
struct FirstView: View {
var body: some View {
Text("Hello, View One!")
CustomNavLink(destination: LastView()
.customNavigationTitle("Last View").customNavigationSubtitle("subtitle"), label: {
Text("Go to Last View").buttonStyleGreen()
})
}
}
struct LastView: View {
var body: some View {
Text("Last View")
}
}
这是我的 GitHub 代码库,其中包含我创建的结构体以构建此自定义导航视图。