I've got 4 ViewControllers attached to a NavigationController. The order of them is 1->2->3->4. When the user presses the back button on 4, I'd like them to be redirected to 2 instead of 3. At the same time, I'd also like the user to be directed back to 2 when the back button is pressed on 3. Is this possible? Thanks in advance.
-
Use unwind segue, there are many similar answers. Here is oneIdan– Idan2016-11-30 05:56:53 +00:00Commented Nov 30, 2016 at 5:56
-
If you want swift answer then have a look at this one stackoverflow.com/questions/31878108/…Nirav D– Nirav D2016-11-30 05:59:16 +00:00Commented Nov 30, 2016 at 5:59
-
use unwined segue stackoverflow.com/questions/12561735/…Cruz– Cruz2016-11-30 08:24:46 +00:00Commented Nov 30, 2016 at 8:24
Add a comment
|
3 Answers
Of course you can do this. Simply create the left bar button on 4th ViewController. and on that button action pop to 2nd viewcontroller
if let viewcontroller = self.navigationController?.viewControllers[1] where viewcontroller.isKindOfClass(YourController) {
self.navigationController?.popToViewController(viewcontroller, animated: false) }
3 Comments
Thomas G.
Small changes in Swift3: if let viewcontroller = self.navigationController?.viewControllers[1], viewcontroller is YourViewController { let _ = self.navigationController?.popToViewController(viewcontroller, animated: false) }
qunayu
Thank you! It worked. Another question because I'm an absolute beginner: How do I assign this to a back button? I looked through the list of UIBarButtonSystemItems but there doesn't seem to be a back button available.
Sahil
on 4th viewcontroller viewDidload self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style:.Plain, target: self, action:#selector(self.back(_:))) and action func backButtonAction(sender: AnyObject) { if let viewcontroller = self.navigationController?.viewControllers[1] where viewcontroller.isKindOfClass(YourController) { self.navigationController?.popToViewController(viewcontroller, animated: false) } }
if let vc = self.viewControllerWithClass(YourVC.self) {
self.popToViewController(vc, animated: true)
}
extension UINavigationController {
func viewControllerWithClass(_ aClass: AnyClass) -> UIViewController? {
for vc in self.viewControllers {
if vc.isMember(of: aClass) {
return vc
}
}
return nil
}
}