简体   繁体   中英

iOS: How to programmatically add a view to a storyboard view

Scenario: I am developing a hybrid Cordova (Phonegap) app for iOS. 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.

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

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

I already implemented this by deriving from Cordova's standard app delegate, but this must have been the wrong way to do it. 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:

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.

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. 例

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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