Skip to content

Instantly share code, notes, and snippets.

@ochim
Created April 6, 2020 11:30
Show Gist options
  • Save ochim/9013b0175d16c56500daf8de016aba80 to your computer and use it in GitHub Desktop.
Save ochim/9013b0175d16c56500daf8de016aba80 to your computer and use it in GitHub Desktop.
[iOS]SwitchViewControllerProtocol
protocol SwitchViewControllerProtocol: UIViewController {
    var childViewController: UIViewController? {get set}
}

extension SwitchViewControllerProtocol {

    func switchChildViewController(_ viewController: UIViewController) {
        childViewController = viewController
        childViewController!.view.translatesAutoresizingMaskIntoConstraints = false
        self.addChild(childViewController!)
        addSubview(subView: childViewController!.view, toView: self.view)
    }

    func addSubview(subView: UIView, toView parentView: UIView) {
        parentView.addSubview(subView)

        var viewBindingsDict = [String: AnyObject]()
        viewBindingsDict["subView"] = subView
        parentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[subView]|",
                                                                 options: [], metrics: nil, views: viewBindingsDict))
        parentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[subView]|",
                                                                 options: [], metrics: nil, views: viewBindingsDict))
    }

    func resetChildViewController() {
        childViewController?.view.removeFromSuperview()
        childViewController?.removeFromParent()
        childViewController = nil
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment