NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];
// [navigationArray removeAllObjects]; // This is just for remove all view controller from navigation stack.
[navigationArray removeObjectAtIndex: 2]; // You can pass your index here
self.navigationController.viewControllers = navigationArray;
[navigationArray release];
Hope this will help you.
Edit: Swift Code
guard let navigationController = self.navigationController else { return }
var navigationArray = navigationController.viewControllers // To get all UIViewController stack as Array
navigationArray.remove(at: navigationArray.count - 2) // To remove previous UIViewController
self.navigationController?.viewControllers = navigationArray
Edit: To remove all ViewController except last one -> no Back Button in the upper left corner
guard let navigationController = self.navigationController else { return }
var navigationArray = navigationController.viewControllers // To get all UIViewController stack as Array
let temp = navigationArray.last
navigationArray.removeAll()
navigationArray.append(temp!) //To remove all previous UIViewController except the last one
self.navigationController?.viewControllers = navigationArray
You can first get all the view controllers in the array and then after checking with the corresponding view controller class, you can delete the one you want.
If you are trying to move to 2nd view controller from 5th view controller (skipping 3rd and 4th), you would like to use [self.navigationController popToviewController:secondViewController].
You can obtain the secondViewController from the navigation controller stack.
I tried other ways like [tempVC removeFromParentViewController];. It make weird behaviour, removed ViewController navigation still showing when pop back like reported by @robin-ellerkmann
I wrote an extension with method which removes all controllers between root and top, unless specified otherwise.
extension UINavigationController {
func removeControllers(between start: UIViewController?, end: UIViewController?) {
guard viewControllers.count > 1 else { return }
let startIndex: Int
if let start = start {
guard let index = viewControllers.index(of: start) else {
return
}
startIndex = index
} else {
startIndex = 0
}
let endIndex: Int
if let end = end {
guard let index = viewControllers.index(of: end) else {
return
}
endIndex = index
} else {
endIndex = viewControllers.count - 1
}
let range = startIndex + 1 ..< endIndex
viewControllers.removeSubrange(range)
}
}
If you want to use range (for example: 2 to 5) you can just use
let range = 2 ..< 5
viewControllers.removeSubrange(range)