Skip to content

Instantly share code, notes, and snippets.

@vinhnx
Created January 23, 2024 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vinhnx/914f3d0ed16cf0b0fa0a976261da0529 to your computer and use it in GitHub Desktop.
Save vinhnx/914f3d0ed16cf0b0fa0a976261da0529 to your computer and use it in GitHub Desktop.
UIViewController container
import UIKit
extension UIViewController {
func nxv_addChildViewController(_ childVC: UIViewController, containerView: UIView) {
addChild(childVC)
containerView.addSubview(childVC.view)
containerView.translatesAutoresizingMaskIntoConstraints = false
childVC.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
childVC.view.topAnchor.constraint(equalTo: containerView.topAnchor),
childVC.view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
childVC.view.leftAnchor.constraint(equalTo: containerView.leftAnchor),
childVC.view.rightAnchor.constraint(equalTo: containerView.rightAnchor)
])
childVC.didMove(toParent: self)
}
func nxv_removeFromParentViewController() {
willMove(toParent: nil)
view.removeFromSuperview()
removeFromParent()
}
func nxv_exchangeViewControllerA(_ viewControllerA: UIViewController,
with viewControllerB: UIViewController,
containerView: UIView,
rootViewController: UIViewController) {
viewControllerA.nxv_removeFromParentViewController()
rootViewController.nxv_addChildViewController(viewControllerB, containerView: containerView)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment