Sobes.tech
Junior — Middle

How to embed one ViewController inside another in an iOS application?

sobes.tech AI

Answer from AI

To embed one UIViewController inside another in iOS, the mechanism of child view controllers is used. This allows organizing complex interfaces from multiple controllers.

Example:

let childVC = ChildViewController()

// Add child controller
addChild(childVC)

// Add its view to the view hierarchy
view.addSubview(childVC.view)
childVC.view.frame = view.bounds // or set the desired frame
childVC.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

// Notify the child controller that it has been added
childVC.didMove(toParent: self)

To remove a child controller:

childVC.willMove(toParent: nil)
childVC.view.removeFromSuperview()
childVC.removeFromParent()

This approach allows proper management of the controllers' lifecycle and hierarchy.

How to embed one ViewController inside another in an… - sobes.tech