// // VCEmbeder.swift // Runner // // Created by Zohaib Iqbal Kambrani on 08/06/2021. // Copyright © 2021 The Chromium Authors. All rights reserved. // import Foundation extension UIView { func fill(to parent: UIView, animateDuration:Double = 0.5) { self.topAnchor.constraint(equalTo: parent.topAnchor).isActive = true self.leadingAnchor.constraint(equalTo: parent.leadingAnchor).isActive = true self.bottomAnchor.constraint(equalTo: parent.bottomAnchor).isActive = true self.trailingAnchor.constraint(equalTo: parent.trailingAnchor).isActive = true UIView.animate(withDuration: animateDuration) { parent.layoutIfNeeded() } } func fillToParent(animateDuration:Double = 0.5) { if let parent = self.superview{ self.topAnchor.constraint(equalTo: parent.topAnchor).isActive = true self.leadingAnchor.constraint(equalTo: parent.leadingAnchor).isActive = true self.bottomAnchor.constraint(equalTo: parent.bottomAnchor).isActive = true self.trailingAnchor.constraint(equalTo: parent.trailingAnchor).isActive = true UIView.animate(withDuration: animateDuration) { parent.layoutIfNeeded() } } } func fillInTo(view:UIView) { view.addSubview(self) fillToParent() } } class ViewEmbedder { class func embed( parent:UIViewController, container:UIView, child:UIViewController, previous:UIViewController?){ if let previous = previous { removeFromParent(vc: previous) } child.willMove(toParent: parent) parent.addChild(child) container.addSubview(child.view) child.didMove(toParent: parent) let w = container.frame.size.width; let h = container.frame.size.height; child.view.frame = CGRect(x: 0, y: 0, width: w, height: h) child.view.backgroundColor = UIColor.black child.view.fill(to: container) } class func removeFromParent(vc:UIViewController){ vc.willMove(toParent: nil) vc.view.removeFromSuperview() vc.removeFromParent() } class func embed(withIdentifier id:String, parent:UIViewController, container:UIView, completion:((UIViewController)->Void)? = nil){ let vc = parent.storyboard!.instantiateViewController(withIdentifier: id) embed( parent: parent, container: container, child: vc, previous: parent.children.first ) completion?(vc) } }