ViewControllerを別のViewControllerの任意ビューにはめ込む処理

public extension UIView {

    public func fillSuperviewWithConstaints() {

        let constraints = NSLayoutConstraint.constraints(fillingSuperviewOf: self)

        if #available(iOS 8, *) {
            NSLayoutConstraint.activate(constraints)
        } else {
            if let superview = superview {
                superview.addConstraints(constraints)
            }
        }
    }

}

public extension NSLayoutConstraint {

    public static func constraints(fillingSuperviewOf view: UIView) -> [NSLayoutConstraint] {
        guard let superview = view.superview else {
            return []
        }

        return [NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: superview, attribute: .top, multiplier: 1.0, constant: 0.0),
                NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: superview, attribute: .bottom, multiplier: 1.0, constant: 0.0),
                NSLayoutConstraint(item: view, attribute: .leading, relatedBy: .equal, toItem: superview, attribute: .leading, multiplier: 1.0, constant: 0.0),
                NSLayoutConstraint(item: view, attribute: .trailing, relatedBy: .equal, toItem: superview, attribute: .trailing, multiplier: 1.0, constant: 0.0),
        ]
    }

}

public extension UIViewController {

    public func addChildViewController(_ childViewController: UIViewController, filling parentView: UIView, withContraints: Bool) {

        addChildViewController(childViewController)
        childViewController.didMove(toParentViewController: self)

        if let subView = childViewController.view {
            parentView.addSubview(subView)

            if withContraints {
                subView.translatesAutoresizingMaskIntoConstraints = false
                subView.fillSuperviewWithConstaints()
            } else {
                subView.frame = parentView.bounds
            }
        }
    }

}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です