Skip to content

Instantly share code, notes, and snippets.

@cntrump
Created June 17, 2025 14:25
Show Gist options
  • Save cntrump/5c8819c4312919d9b8367b4edd169766 to your computer and use it in GitHub Desktop.
Save cntrump/5c8819c4312919d9b8367b4edd169766 to your computer and use it in GitHub Desktop.
This UIViewController extension provides methods to easily embed and detach a child view controller, managing its view hierarchy and layout within a parent view controller.
// details: https://developer.apple.com/documentation/uikit/creating-a-custom-container-view-controller
extension UIViewController {
@objc(attachToParentViewController:layout:)
public func attach(toParent parent: UIViewController?, layout: (@MainActor (UIView) -> Void)? = nil) {
guard let parent else {
return
}
parent.addChild(self)
if let contentView = view {
parent.view.addSubview(contentView)
if let layout {
layout(contentView)
} else {
contentView.frame = parent.view.bounds
contentView.translatesAutoresizingMaskIntoConstraints = true
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
}
didMove(toParent: parent)
}
@objc(detachFromParentViewController)
public func detachFromParent() {
willMove(toParent: nil)
view.removeFromSuperview()
removeFromParent()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment