Edmund Edmund - 2 months ago 10x
iOS Question

Swift + Storyboards: How to keep strong reference to show segue controller?

I have two controllers:

  1. HistoryViewController, which has a "Browse" button. This is embedded inside a NavigationController

  2. WebBrowserViewController, which will be accessed through the browse button from the HistoryViewController

The browse button is hooked up fine. When I tap on it, it takes me to the web browser view storyboard.

enter image description here

However, it always makes a new web browser view when I press back and tap on the "Browse" button again. Therefore, if I'm on a certain page in the web browser view and I go back to the history view, and then tap "Browse" again, I always go back to the homepage and lose my current page.

Is there a way to keep a strong reference to the WebBrowserViewController so that only the initial tap to the "Browse" button will create the web browser and all following taps just show that one?

I'm using storyboards.


Segues always create a new viewController. If you want to return to the same WebBrowserViewController repeatedly, then you should instantiate that view controller manually, keep a strong reference to it in your HistoryViewController, and then push or present that viewController instead of using a segue.

var webBrowserVC: WebBrowserViewController?

@IBAction func browseButtonPressed() {
    if webBrowserVC == nil {
        webBrowserVC = storyboard?.instantiateViewControllerWithIdentifier("webBrowserViewController") as? WebBrowserViewController

    // configure webBrowserVC with data that would have previously been set
    // in prepareForSegue:
    webBrowserVC?.someProperty = someData

    // push view controller if you are using a navigation controller:
    navigationController?.pushViewController(webBrowserVC!, animated: true)

    // or to present modally:
    presentViewController(webBrowserVC!, animated: true, completion: nil)

In order for this to work, you have to set the Storyboard Identifier to "webBrowserViewController" in the Identity Inspector.