xcode 添加故事板视图作为以编程方式创建的视图的子视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13390038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 02:05:53  来源:igfitidea点击:

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

iosxcodecocoa-touchuiviewstoryboard

提问by JeffN

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];

我创建了一个特殊的 UIView 类,它具有某些属性,我以编程方式这样做,因为它通常是空白的,但有时会包含其他视图。我知道如果我以编程方式创建 UIView 我可以做类似的事情[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?

我的问题是我在故事板中创建了一个 UIView,我需要将该 UIView 添加为我的特殊视图的子视图。我已将它连接为 ViewController 中的一个属性,但是当我执行与上述相同的代码时,没有任何反应。想法?

回答by KPM

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.

并且不要忘记在 Interface Builder 中为您的场景(视图控制器)提供这样的标识符。

回答by Vineeth

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

回答by Brian Liang

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.

容纳您想要的视图的 UIViewController 可能不会被实例化。因此,您需要实例化该控制器并从那里获取视图。