How to add a Container View programmatically

后端 未结 4 621
难免孤独
难免孤独 2020-11-30 17:09

A Container View can be easily added into a storyboard through Interface Editor. When added, a Container View is of a placeholder view, an embed segue, and a (child) view co

4条回答
  •  天命终不由人
    2020-11-30 18:10

    Here is my code in swift 5.

    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)
    }
    
    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)
    }
    

    }

    Usage

    @IBOutlet weak var container:UIView!
    
    ViewEmbedder.embed(
        withIdentifier: "MyVC", // Storyboard ID
        parent: self,
        container: self.container){ vc in
        // do things when embed complete
    }
    

    Use the other embed function with non-storyboard view controller.

提交回复
热议问题