Search code examples
iosswiftuinavigationcontrollersegueuinavigationitem

Combine Seques with UINavigationController


I am building a mobile app which displays stats from multiple APIs. The app shows different values based on the API that is active. At runtime, the user can select which API to display values for. However, the values are always displayed within the same Target view controller.

UINavigationController is in use and I'd like to defer to that for navigation and navigation UI, if possible, even though UITableViewControllers support navigation bars.

Please see the storyboard design image at the end of the question.

Environment: iOS 9/Swift 2.2/XCode 7

  1. At runtime, the user will select a Choice view controller from the Select controller. What is the appropriate way to segue from one of the Choice view controllers, via a "Done" UIBarButton, to the Target controller? The Target controller does not change.

  2. Must I programmatically define the right bar button to "Done" for every controller that is embedded within the UINavigationController?

     class UIViewController: UITableViewController {
         override func viewWillAppear( animated: Bool) {
              super.viewWillAppear( animated)
              self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
         }
    }
    

Storyboard Layout


Solution

  • The proper way to return to the root view controller is:

    class MyViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
            self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(MyViewController.done))    
        }
    
    
        func done() {
            if let navigationController = self.navigationController {
                navigationController.popToRootViewController(animated: true)
            }
        }
    }
    

    You do need to programmatically add a "done" button; but it's more simple than that. Just select your root view controller, and copy/past the class in storyboard. Use your segues to push the correct view onto the UINavigation stack.