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

The swift class extension you’ll want to include in all your projects

Here is one of my favorite extension I created for Array. Very useful shortcut when you use abstraction ( as you should ) and you want to create an array from another one.

Description

Instantiate an Array of type A with an another array of type ( or protocol ) B and fills it with elements from B that can be cast to A.

Code

Example

Screen Shot 2016-06-08 at 2.57.33 PM

You could always use .filter but it would take way more lines.  I often use it to get a specific subview in my view hierarchy.  Here’s the link to the playground file.

MABDev.ArrayExtension.playground

That’s it for today folks !  See you soon. MAB.