How can I add a native view from a Cordova plugin

2019-04-16 18:21发布

问题:

I am developing a plugin with the latest version of Cordova (3.3). I need to add a native UIImageView to the Cordova view.

If I have access to the project for example in the platform folder, I can add my view to the view instance belonging to CDVViewController. However, I am not sure how to access that reference from a plugin.

Inside my plugin I have:

@interface CDVCool : CDVPlugin

@property (weak, nonatomic) UIImageView *nativeImageView;
...
@end

How can I initialize and render this view by modifying only the plugin files?

回答1:

Credit for this answer goes to devgeeks who pointed me to a couple of his plugins, MapKit and VolumeSlider, that mix in native elements with cordova web view.

The key is to overwrite the initWithWebView method:

-(CDVPlugin*) initWithWebView:(UIWebView*)theWebView
{
    self = (VolumeSlider*)[super initWithWebView:theWebView];
    return self;
}

Now inside the plugin you can obtain a reference to the view controller behind cordova web view and add to it whatever your heart desire.

[self.webView.superview addSubview:mpCustomView];

This is cool becuase you can control the zPosition of any views you add with respect to the webView. So you can put views above or below the web view.