[英]Pop to the root view controller when the navigation bar's built in back button is pressed
Whenever the back button is pressed on my top view controller I want to go back to a specific view controller that is not the previous view controller.每当在我的顶视图控制器上按下后退按钮时,我想返回到一个特定的视图控制器,而不是前一个视图控制器。 I was hoping there was a way to override the functionality of the back button in some way.
我希望有一种方法可以以某种方式覆盖后退按钮的功能。
EDIT:编辑:
I got this to work:我得到了这个工作:
self.navigationController?.popToRootViewController(animated: true)
The only issue is as it is animating it shows the intermediate view controller as its going to the root.唯一的问题是因为它正在动画它显示中间视图控制器作为它的根。
Reading your edited question, it seems that what you are looking for is to pop back to the root view controller in the navigation stack without the animation revealing any view controllers in between.阅读您编辑的问题,您似乎正在寻找的是弹出回到导航堆栈中的根视图控制器,而动画不会显示其间的任何视图控制器。
You can easily achieve this by removing all those middle view controllers from the stack.您可以通过从堆栈中删除所有这些中间视图控制器来轻松实现这一点。
In the viewDidLoad
method of your last shown view controller do:在上次显示的视图控制器的
viewDidLoad
方法中,请执行以下操作:
func viewDidLoad() {
super.viewDidLoad()
if let rootVC = navigationController?.viewControllers.first {
navigationController?.viewControllers = [rootVC, self]
}
}
Then, when tapping on the back button, the navigation controller will dismiss the current view controller going back to the root.然后,当点击后退按钮时,导航控制器将关闭当前视图控制器返回到根。
Based on apple developer documentation :基于苹果开发者文档:
A navigation controller object manages its child view controllers using an ordered array, known as the navigation stack.
导航控制器对象使用称为导航堆栈的有序数组管理其子视图控制器。 The first view controller in the array is the root view controller and represents the bottom of the stack.
数组中的第一个视图控制器是根视图控制器,代表堆栈的底部。 The last view controller in the array is the topmost item on the stack, and represents the view controller currently being displayed.
数组中的最后一个视图控制器是堆栈中最顶层的项目,代表当前显示的视图控制器。 You add and remove view controllers from the stack using segues or using the methods of this class .
您可以使用 segues 或使用此类的方法从堆栈中添加和删除视图控制器。
for achieving the pop without animation you should do:为了在没有动画的情况下实现流行,您应该这样做:
var viewControllers: [UIViewController] The view controllers currently on the navigation stack.
var viewControllers: [UIViewController] 当前在导航堆栈上的视图控制器。
example:例子:
yourViewController.navigationController.viewControllers = [specificVC,self]
import UIKit
extension: UIViewController {
func setNext(to root: UIViewController? = nil) {
guard let navigation = self.navigationController,
let first = navigation.viewControllers.first else {return}
if let root = root {
navigation.viewControllers = [root,self]
}else{
navigation.viewControllers = [first,self]
}
}
}
self.setNext(to: specificVC)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.