LoginSignup
4
3

More than 5 years have passed since last update.

[iOS] メソッドを呼ぶだけでContainerに子どもを追加できるUIViewControllerのエクステンション

Last updated at Posted at 2016-08-03

コンテナに子どもを追加するのを、IBからではなくコードから設定する時に簡単に設定できるようエクステンションを書いてみました。
指摘事項あればどんどん言っていただけると幸いです。

UIViewController+Container.swift

import UIKit

extension UIViewController {

    /**
     コンテナに子どもビューを設定する
     - parameter childStoryboardName: 子どものストーリーボードのファイル名
     - parameter childStoryboardId: 子どものストーリーボードID
     - parameter containerView: 子どもを設定したいコンテナ
     */
    func addChildrenToContainer(childStoryboardName: String, childStoryboardId: String, containerView: UIView) {

        let storyboard = UIStoryboard(name: childStoryboardName, bundle: nil)
        let controller = storyboard.instantiateViewControllerWithIdentifier(childStoryboardId)

        self.addChildViewController(controller)

        let view = controller.view

        // AutoLayoutを解除する
        view.translatesAutoresizingMaskIntoConstraints = false

        var viewBindingsDict = [String: AnyObject]()
        viewBindingsDict["subView"] = view

        // 制約を付与する前に追加すること
        containerView.addSubview(view)

        // コンテナに子どもをセットしたからといってコンテナ内にきれいに収まるわけではない
        containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
            "H:|[subView]|",
            options: [],
            metrics: nil,
            views: viewBindingsDict))
        containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
            "V:|[subView]|",
            options: [],
            metrics: nil,
            views: viewBindingsDict))

        controller.didMoveToParentViewController(self)
    }
}
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3