Created
June 17, 2025 14:25
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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