Search code examples
swiftviewcontroller

Hide / Show View Controller instead of Add / Remove to Parent


I have a view controller A. In this View Controller, I have a button and tapping on that button display a View Controller B which has a webview.

I want to hide that webview containing view controller (B) instead of removing it and I want to instantiate this webview once in a lifecycle period.

Basicaly, I want to instantiate a view controller only once and want to hide (not remove) it so that later I can continue with that state of the hidden view controller.

How can I achieve this?


Solution

  • The requirement was -> From ViewController A, If user opens ViewController B then ViewController B will be displayed which contains only a webView.

    Once user presses Save button on a ViewController B then the ViewController B will be closed (i.e. that will be removed from view hierarchy) and user will be navigate back to ViewController A.

    And that time I need to save the ViewController B, so that later user can be displayed the loaded WebView, instead of initializing the ViewController B again.

    Solution:
    I've solved this requirement by creating a static dictionary of type String:ViewController (used a string as a key). Later when I need to display the loaded ViewController B then I can just search in that static dictionary and if found then the loaded ViewController can be displayed to the user.

    private var viewControllers: [String: UIViewController] = [:]
        
    func addViewController(_ viewController: UIViewController, for key: String) {
        viewControllers[key] = viewController
    }
    
    func getViewController(for key: String) -> UIViewController? {
        viewControllers[key]
    }
    
    func deleteViewControllers() {
        viewControllers.removeAll()
    }
    

    I've used these three function to save access and delete ViewController B.