Add a storyboard view as a subview of a programmatically created view

元气小坏坏 提交于 2019-12-21 11:12:05

问题


I have created a special class of UIView that has certain properties, and I did so programmatically because it is usually blank but will at times contain other views. I know that if I create a UIView programmatically I can do something like [specialView addSubview: aView];

My problem is that there is a UIView that I created in storyboard and I need to add that UIView as a subview on my special view. I have connected it as a property in my ViewController but when I do the same code as above, nothing happens. Thoughts?


回答1:


MyViewController *myViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"MyScene"]; 
[specialView addSubview:myViewController.theViewToAdd]; 

And don't forget to give such an identifier to your scene (view controller) in Interface Builder.




回答2:


Another solution is you can add the viewcontroller as a childviewcontroller.

    func displayContentController(content: UIViewController) {
    addChildViewController(content)
    self.view.addSubview(content.view)
    content.didMoveToParentViewController(self)
}

To remove :

func hideContentController(content: UIViewController) {
    content.willMoveToParentViewController(nil)
    content.view.removeFromSuperview()
    content.removeFromParentViewController()
}



回答3:


That UIViewController which houses the view you want may not be instantiated. So you would need to instantiate that controller and grab the view from there.



来源:https://stackoverflow.com/questions/13390038/add-a-storyboard-view-as-a-subview-of-a-programmatically-created-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!