Created
November 13, 2025 09:17
-
-
Save dterekhov/20580d37235a416170ce68312cdb6221 to your computer and use it in GitHub Desktop.
UIViewController+Embed: Embeds a newly created view controller of the given type into a container view #uikit #swift-api #real-project
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
| import UIKit | |
| extension UIViewController { | |
| /// Embeds a newly created view controller of the given type into a container view. | |
| /// - Parameters: | |
| /// - vcType: The type of the view controller to embed. | |
| /// - containerView: The container view that will hold the embedded view. | |
| /// - setup: Optional configuration closure executed after the view is added. | |
| public func fw_initEmbedVC(ofType vcType: UIViewController.Type, | |
| inside containerView: UIView, | |
| setup: ((UIViewController) -> Void)? = nil) { | |
| let embedVC = vcType.init() | |
| fw_initEmbedVC(embedVC, inside: containerView, setup: setup) | |
| } | |
| /// Embeds an existing view controller instance into a container view. | |
| /// - Parameters: | |
| /// - embedVC: The view controller instance to embed. | |
| /// - containerView: The container view that will hold the embedded view. | |
| /// - setup: Optional configuration closure executed after the view is added. | |
| public func fw_initEmbedVC(_ embedVC: UIViewController, | |
| inside containerView: UIView, | |
| setup: ((UIViewController) -> Void)? = nil) { | |
| addChild(embedVC) | |
| embedVC.view.translatesAutoresizingMaskIntoConstraints = false | |
| containerView.addSubview(embedVC.view) | |
| NSLayoutConstraint.activate([ | |
| embedVC.view.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), | |
| embedVC.view.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), | |
| embedVC.view.topAnchor.constraint(equalTo: containerView.topAnchor), | |
| embedVC.view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor) | |
| ]) | |
| setup?(embedVC) | |
| embedVC.didMove(toParent: self) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment