UIViewController extension for child view controller containment.

Hello !  I know its been a while, holidays and all …

Here’s a little extension that does no magic but shortens your code if you have to load child view controller from storyboards.  Sorry for the lack of syntax colouring, WordPress does not seem to support Swift yet.

[code language=”text”]
import Foundation

typealias ViewControllerStoryboardInfo = (name: String, id: String?)

protocol Container {
}

extension Container where Self: UIViewController {

func addChildViewController(withInfo info: ViewControllerStoryboardInfo)-> UIViewController? {

var viewController: UIViewController! = nil

switch info.id {
case let identifier where identifier != nil:
viewController = UIStoryboard(name: info.name, bundle: nil).instantiateViewController(withIdentifier: identifier!)
default:
viewController = UIStoryboard(name: info.name, bundle: nil).instantiateInitialViewController()
}

if let viewController = viewController {

self.addChildViewController(viewController)
viewController.view.frame = self.view.bounds
self.view.addSubview(viewController.view)
viewController.didMove(toParentViewController: self)
return viewController
}

return nil
}

func removeAllChildViewController() {
self.childViewControllers.forEach({ (controller) in
controller.view.removeFromSuperview()
controller.willMove(toParentViewController: nil)
controller.removeFromParentViewController()
})
}
}
[/code]

 

Cheers,

MAB

Leave a Reply

Your email address will not be published. Required fields are marked *