Search code examples
uinavigationcontrollerpresentviewcontroller

navigationController!.pushViewController vs. presentViewController in iOS Swift


What are the implications of pushing a ViewController in UINavigation vs. presenting a ViewController modally in terms of changing values in the next view?

For example, why does the first work but not the second?

First:

var textController: TextViewController
textController = self.storyboard!.instantiateViewControllerWithIdentifier("TextViewController") as! TextViewController
presentViewController(textController, animated: false, completion: nil)
textController.textDetail.text = Categories[indexPath.row]

Second:

var textController: TextViewController
textController = self.storyboard!.instantiateViewControllerWithIdentifier("TextViewController") as! TextViewController
self.navigationController!.pushViewController(textController,animated:true)
textController.textDetail.text = Categories[indexPath.row]

I can't get the label's value to change when pushing in a navigation stack.


Solution

  • It appears as though when calling the presentViewController method, the view of the view controller is actually loaded during the call, whereas when calling the pushViewController on the navigation controller, the view itself is loaded after the call.

    You can test this yourself by printing to the console before and after presenting/pushing the view controller, and printing to the console in the TextViewController's viewDidLoad method.

    The view needs to be loaded for the textDetail variable to load (you haven't said so, but I'm assuming this is an IBOutlet) and the textDetail variable needs to load for you to be able to modify its text property.

    To use pushViewController you could for example set a variable on your TextViewController class, and override its viewDidLoad method, where you could then set the text property on the textDetail variable.