简体   繁体   English

iOS:如何以编程方式将视图添加到情节提要视图

[英]iOS: How to programmatically add a view to a storyboard view

Scenario: I am developing a hybrid Cordova (Phonegap) app for iOS. 场景:我正在为iOS开发混合式Cordova(Phonegap)应用程序。 To mix native and Cordova code, I set up a storyboard in Xcode 7 where a UIView is embedded in a container view (using an embed segue), to be able to re-use the web view throughout the native app. 为了混合本机代码和Cordova代码,我在Xcode 7中设置了一个故事板,其中UIView嵌入在容器视图中(使用embed segue),以便能够在整个本机应用程序中重复使用Web视图。

For the embedding of a Cordova view, I found these instructions: http://cordova.apache.org/docs/en/edge/guide_platforms_ios_webview.md.html#iOS%20WebViews 为了嵌入Cordova视图,我找到了以下说明: http : //cordova.apache.org/docs/en/edge/guide_platforms_ios_webview.md.html#iOS%20WebViews

which are basically saying that you have to call this: 基本上是说您必须调用此命令:

CDVViewController* viewController = [CDVViewController new];
viewController.view.frame = CGRectMake(0, 0, 320, 480);
[myView addSubview:viewController.view];

but they do not explain how to add the view to a storyboard view. 但他们没有说明如何将视图添加到情节提要视图中。 I am especially asking myself how to deal with the CGRectMake thing, as I want the view to render responsively, ie adjust itself to the parent view's constraints (instead of having a fixed rectangle). 我特别问自己如何处理CGRectMake,因为我希望视图能够响应性地渲染,即调整自身以适应父视图的约束(而不是具有固定的矩形)。

I already implemented this by deriving from Cordova's standard app delegate, but this must have been the wrong way to do it. 我已经从Cordova的标准应用程序委托派生了这个实现,但是这样做肯定是错误的方法。 When I call Cordova's camera, take a picture and come back to my web view, the web view suddenly jumps out of it's borders (to the top of the window), and I see this error message in the Xcode console: 当我给Cordova的摄像机打电话时,拍照并返回到Web视图,该Web视图突然跳出边界(到窗口顶部),并且在Xcode控制台中看到以下错误消息:

Presenting view controllers on detached view controllers is discouraged

PS: I am actually using Swift, but I'm able to read Objective-C code, so a code sample in any of these languages is fine for me. PS:我实际上是在使用Swift,但是我能够阅读Objective-C代码,因此使用这些语言中的任何一种的代码示例都适合我。

Simply create an outlet for the view that exists in your storyboard, connect it and add the subview 只需为情节提要中存在的视图创建一个出口,将其连接并添加子视图

@IBOutlet weak var containerView: UIView!

func addMySubview() {
 var viewController = CDVViewController()
 viewController.view.frame = containerView.frame
 containerView.addSubview(viewController.view)
}

Edit: Here, I did an example in a playground so you can see how your view's frame changes with the parents. 编辑:在这里,我在操场上做了一个示例,以便您可以查看视图框架如何与父母一起变化。 例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM