如何在ios的布局中添加cordovaios webview 添加控件

iOS开发中WebView的基本使用方法简介
作者:容芳志
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了iOS开发中WebView的基本使用方法,代码基于传统的Objective-C,需要的朋友可以参考下
1、使用UIWebView加载网页
运行XCode 4.3,新建一个Single View Application,命名为WebViewDemo。
2、加载WebView
在ViewController.h添加WebView成员变量和在ViewController.m添加实现
#import &UIKit/UIKit.h&
@interface ViewController : UIViewController
&&& UIWebView *webV
ViewController.m
- (void)viewDidLoad
&&& [super viewDidLoad];
&&& webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
&&& NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:@""]];
&&& [self.view addSubview: webView];
&&& [webView loadRequest:request];
运行,这样百度网页就打开了
手机的网络环境是实时变化的,网络慢的时候,怎么提示用户网页正在打开呢?在网页打开出错的时候怎么提示用户呢?这时候我们就需要知道网页什么时候打开的,
什么时候加载完成,什么时候出错了。那么我们需要实现这个&UIWebViewDelegate&协议
3、实现协议,在ViewController.h修改如下:
#import &UIKit/UIKit.h&&
@interface ViewController : UIViewController&UIWebViewDelegate&&
&&& UIWebView *webV&
按住control+command+向上键,切换到ViewController.m文件,这是我们在文件中打入- (void) webView,就能看到如下实现方法:
4、UIWebView主要有下面几个委托方法:
1、- (void)webViewDidStartLoad:(UIWebView *)webV开始加载的时候执行该方法。
2、- (void)webViewDidFinishLoad:(UIWebView *)webV加载完成的时候执行该方法。
3、- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)加载出错的时候执行该方法。
我们可以将activityIndicatorView放置到前面两个委托方法中。
- (void)webViewDidStartLoad:(UIWebView *)webView
&&& [activityIndicatorView startAnimating] ;
- (void)webViewDidFinishLoad:(UIWebView *)webView
&&& [activityIndicatorView stopAnimating];
buttonPress方法很简单,调用我们开始定义好的loadWebPageWithString方法就行了:
- (IBAction)buttonPress:(id) sender
&&& [textField resignFirstResponder];
&&& [self loadWebPageWithString:textField.text];
当请求页面出现错误的时候,我们给予提示:
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
&&& UIAlertView *alterview = [[UIAlertView alloc] initWithTitle:@"" message:[error localizedDescription]& delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
&&& [alterview show];
&&& [alterview release];
5、加载等待界面
为了给用户更直观的界面效果,我们加上等待的loading界面试试
在webViewDidStartLoad加入等待
&strong&- (void) webViewDidStartLoad:(UIWebView *)webView
&&& //创建UIActivityIndicatorView背底半透明View&&&&
&&& UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];&
&&& [view setTag:108];&
&&& [view setBackgroundColor:[UIColor blackColor]];&
&&& [view setAlpha:0.5];&
&&& [self.view addSubview:view];&
&&& activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];&
&&& [activityIndicator setCenter:view.center];&
&&& [activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];&
&&& [view addSubview:activityIndicator];&
&&& [activityIndicator startAnimating];
&& &/strong&
加载完成或失败时,去掉loading效果
&strong&- (void) webViewDidFinishLoad:(UIWebView *)webView
&&& [activityIndicator stopAnimating];
&&& UIView *view = (UIView*)[self.view viewWithTag:108];
&&& [view removeFromSuperview];
&&& NSLog(@"webViewDidFinishLoad");
- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
&&& [activityIndicator stopAnimating];
&&& UIView *view = (UIView*)[self.view viewWithTag:108];
&&& [view removeFromSuperview];
&&& &/strong&
运行效果:
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!&&|&&
LOFTER精选
网易考拉推荐
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
&?xml version="1.0" encoding="UTF-8"?&
&preference name="KeyboardDisplayRequiresUserAction" value="true" /&
&preference name="SuppressesIncrementalRendering" value="false" /&
&preference name="UIWebViewBounce" value="true" /&
&preference name="TopActivityIndicator" value="gray" /&
&preference name="EnableLocation" value="false" /&
&preference name="EnableViewportScale" value="false" /&
&preference name="AutoHideSplashScreen" value="true" /&
&preference name="ShowSplashScreenSpinner" value="true" /&
&preference name="MediaPlaybackRequiresUserAction" value="false" /&
&preference name="AllowInlineMediaPlayback" value="false" /&
&preference name="OpenAllWhitelistURLsInWebView" value="false" /&
&preference name="BackupWebStorage" value="cloud" /&
&plugin name="LocalStorage" value="CDVLocalStorage" /&
&plugin name="Device" value="CDVDevice" /&
&plugin name="Logger" value="CDVLogger" /&
&plugin name="Compass" value="CDVLocation" /&
&plugin name="Accelerometer" value="CDVAccelerometer" /&
&plugin name="Camera" value="CDVCamera" /&
&plugin name="NetworkStatus" value="CDVConnection" /&
&plugin name="Contacts" value="CDVContacts" /&
&plugin name="Debug Console" value="CDVDebugConsole" /&
&plugin name="File" value="CDVFile" /&
&plugin name="FileTransfer" value="CDVFileTransfer" /&
&plugin name="Geolocation" value="CDVLocation" /&
&plugin name="Notification" value="CDVNotification" /&
&plugin name="Media" value="CDVSound" /&
&plugin name="Capture" value="CDVCapture" /&
&plugin name="SplashScreen" value="CDVSplashScreen" /&
&plugin name="Echo" value="CDVEcho" /&
&plugin name="Battery" value="CDVBattery" /&
&plugin name="Globalization" value="CDVGlobalization" /&
&plugin name="InAppBrowser" value="CDVInAppBrowser" /&
&/plugins&
&/cordova&新建config.xml文件,添加到项目中。&&2 创建www目录在项目根目录下,创建文件夹www在www文件夹下,新建文件index.html文件范例:&!DOCTYPE html&
&title&&/title&
&meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=" /&
&meta charset="utf-8"&
&script type="text/javascript" charset="utf-8" src="cordova.ios.js"&&/script&
&script type="text/javascript"&
function onBodyLoad()
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady()
window.pageIsLoaded = true;
navigator.notification.alert("Cordova is working")
&body onload="onBodyLoad()"&
&p&Hello World!&/p&
&/html&“Create folder references for any added folder”,添加到项目中&1、添加CordovaLib子项目cordova-2.3.0/cordova-ios/CordovaLib下,将CordovaLib.xcodeproj拖拽到项目中TARGET-& Build Settings -& Other Linker Flags,添加&-all_load&和&-Obj-C&TARGET -& Build Phases -&&Link Binaries with Libraries,添加一下frameworks:AddressBook.frameworkAddressBookUI.frameworkAudioToolbox.frameworkAVFoundation.frameworkCoreLocation.frameworkMediaPlayer.frameworkQuartzCore.frameworkSystemConfiguration.frameworkMobileCoreServices.frameworkCoreMedia.frameworkTARGET -& Build Phases -&&Target Dependencies,添加CordovaLibTARGET -& Build Phases -&&Link Binaries with Libraries,添加CordovaLia.aTARGET-& Build Settings -& Header Search Path,添加一下项:(注意:带引号)"$(TARGET_BUILD_DIR)/usr/local/lib/include""$(OBJROOT)/UninstalledProducts/include""$(BUILT_PRODUCTS_DIR)"&&2、使用新建CDVViewController子类示例:#import &UIKit/UIKit.h&
#import &Cordova/CDVViewController.h&
@interface ViewController : CDVViewController
@end&设置该对象的wwwFolderName属性,startPage属性示例:#import "AppDelegate.h"
#import "ViewController.h"
@implementation AppDelegate
- (void)dealloc
[_window release];
[_viewController release];
[super dealloc];
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
self.viewController = [[ViewController new] autorelease];
self.viewController.wwwFolderName = @"www";
self.viewController.startPage = @"index.html";
self.viewController.useSplashScreen = YES;
self.window.rootViewController = self.viewC
[self.window makeKeyAndVisible];
return YES;
阅读(272)|
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
历史上的今天
在LOFTER的更多文章
loftPermalink:'',
id:'fks_',
blogTitle:'iOS 嵌入 Cordova WebView到iOS',
blogAbstract:'参考:
{if x.moveFrom=='wap'}
{elseif x.moveFrom=='iphone'}
{elseif x.moveFrom=='android'}
{elseif x.moveFrom=='mobile'}
${a.selfIntro|escape}{if great260}${suplement}{/if}
{list a as x}
推荐过这篇日志的人:
{list a as x}
{if !!b&&b.length>0}
他们还推荐了:
{list b as y}
转载记录:
{list d as x}
{list a as x}
{list a as x}
{list a as x}
{list a as x}
{if x_index>4}{break}{/if}
${fn2(x.publishTime,'yyyy-MM-dd HH:mm:ss')}
{list a as x}
{if !!(blogDetail.preBlogPermalink)}
{if !!(blogDetail.nextBlogPermalink)}
{list a as x}
{if defined('newslist')&&newslist.length>0}
{list newslist as x}
{if x_index>7}{break}{/if}
{list a as x}
{var first_option =}
{list x.voteDetailList as voteToOption}
{if voteToOption==1}
{if first_option==false},{/if}&&“${b[voteToOption_index]}”&&
{if (x.role!="-1") },“我是${c[x.role]}”&&{/if}
&&&&&&&&${fn1(x.voteTime)}
{if x.userName==''}{/if}
网易公司版权所有&&
{list x.l as y}
{if defined('wl')}
{list wl as x}{/list}在CordovaActivity中添加原生View组件
今天把移动Web站封装成了 App,发现还是用Cordova封装方便,即使没有使用到任何原生的API, 主要是兼容性好,配置比用WebView方便太多了。默认继承的CordovaActivity只有一个WebView,因此没有不方便通过java代码添加View,通过重新makeWebView,createViews 2个方法可以实现使用自定义的layout, 方便的添加自己的原生。
import android.content.I
import android.graphics.C
import android.os.B
import android.view.V
import android.view.animation.DecelerateI
import android.widget.ImageB
import org.apache.cordova.CordovaA
import org.apache.cordova.CordovaWebV
import org.apache.cordova.CordovaWebViewI
import org.apache.cordova.engine.SystemWebV
import org.apache.cordova.engine.SystemWebViewE
public class MainActivity extends CordovaActivity {
* Called when the activity is first created.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
super.init();
loadUrl(launchUrl);
ImageButton btnShare=(ImageButton)findViewById(R.id.btnShare);
btnShare.setAlpha(0f);
btnShare.animate()
.alpha(1f)
.setDuration(1500)
.setInterpolator(new DecelerateInterpolator())
.setStartDelay(1000);
btnShare.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(text/plain);
intent.putExtra(Intent.EXTRA_SUBJECT, 分享);
intent.putExtra(Intent.EXTRA_TEXT, 欢迎访问);
startActivity(Intent.createChooser(intent, 分享到));
protected CordovaWebView makeWebView() {
SystemWebView webView = (SystemWebView)findViewById(R.id.cordovaWebView);
return new CordovaWebViewImpl(new SystemWebViewEngine(webView));
protected void createViews() {
//Why are we setting a constant as the ID? This should be investigated
appView.getView().setId(100);
appView.getView().setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
setContentView(appView.getView());
if (preferences.contains(BackgroundColor)) {
int backgroundColor = preferences.getInteger(BackgroundColor, Color.BLACK);
// Background of activity:
appView.getView().setBackgroundColor(backgroundColor);
appView.getView().requestFocusFromTouch();
更详细的介绍看下面的文章:
Embed Cordova Webview in Android Native App
Some articles have shown how to embed cordova webview to android native application, for example:
http://cordova.apache.org/docs/en/5.0.0/guide_platforms_android_webview.md.html
http://richardgilmour.co.uk//embedding-a-cordova-webview-in-a-native-android-app/
/Adobe-Marketing-Cloud-Apps/app-sample-android-phonegap/wiki/Embed-Webview-in-Android-Fragment
But unfortunately, the latest release of cordova android(4.0.0) make big changes on its code base. This changes, mostly kind of design pattern, have made the methods described in above article not work. What make me confused is that the cordova official website still use the old method in its example, which may waste others a lot of time.
This article will show how to cooperate with the new changes of cordova android to embed cordova webview in native android application.
Create Cordova Android Project
First of all, we need to create a cordova android project. It is better to use cordova-cli.
cordova create test_cordova com.example.hello HelloWorld
cordova platform add android
cordova plugin add nl.x-services.plugins.toast
cordova plugin add org.apache.cordova.device
cordova build
The first line of code create a new cordova project in folder test_cordova.
The second line of code add android platform for new created project.
The third and fourth line of code add two plugin for project(we will use these plugins in the example).
The last line of code build the new created project
Create Native Android Application
Google now suggest Android Studio for building android project, so we will use it here. Create a new project with blank activity using Android Studio. Here, the new created activity is called MainActivity.
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
public void startCordovaActivity(View view) {
Intent intent = new Intent(this, TestCordovaActivity.class);
startActivity(intent);
public void startCordovaActivityWithLayout(View view) {
Intent intent = new Intent(this, TestCordovaWithLayoutActivity.class);
startActivity(intent);
Nothing special, we just define two methods: startCordovaActivity and startCordovaActivity. These two method is bind with two buttons, which we will see later.
startCordovaActivity will transfer to a new activity whose layout is a cordova webview created programmaticly.
startCordovaActivity will transfer to a new activity whose layout is defined using xml layout file and embedded with a cordova webview.
Lets have a look at MainActivity's layout xml file.
Two buttons are defined, corresponding to the two methods above.
TestCordovaActivity
This activity is created to show how to create an activity with a cordova webview without the need of layout xml file.
public class TestCordovaActivity extends CordovaActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
// Load your application
launchUrl = file:///android_asset/www/index.
launchUrl = file:///android_asset/www/index2.
loadUrl(launchUrl);
Noted that we extends the CordovaActivity , which is from cordova library and implement most of stuff in order to cooperate with a cordova webview. We don't need to set the layout xml file usingsetContentView here, because the CordovaActivity create set it for us, a default cordova webview.
TestCordovaWithLayoutActivity
This activity has its layout xml file.
public class TestCordovaWithLayoutActivity extends CordovaActivity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_cordova_with_layout);
super.init();
// Load your application
// launchUrl = file:///android_asset/www/index.html
launchUrl = file:///android_asset/www/index2.
loadUrl(launchUrl);
protected CordovaWebView makeWebView() {
SystemWebView webView = (SystemWebView)findViewById(R.id.cordovaWebView);
return new CordovaWebViewImpl(new SystemWebViewEngine(webView));
protected void createViews() {
//Why are we setting a constant as the ID? This should be investigated
appView.getView().setId(100);
appView.getView().setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
setContentView(appView.getView());
if (preferences.contains(BackgroundColor)) {
int backgroundColor = preferences.getInteger(BackgroundColor, Color.BLACK);
// Background of activity:
appView.getView().setBackgroundColor(backgroundColor);
appView.getView().requestFocusFromTouch();
Again, we need to extend the CordovaActivity. But this time, we use setContentView to set layout xml explicitly. In order to make things work, we need to override two methods: makeWebView andcreateViews.
makeWebView is important, it use the R.id.cordovaWebView, which we define in layout xml file(we will see later).
createViews is not so important, we override it just because it will use setContentView by default. But we want to use our xml, so just comment it.
The activity_test_cordova_with_layout.xml
We use a org.apache.cordova.engine.SystemWebView from cordova library. If you have read the articles listed above, you may remember that most of examples use org.apache.cordova.CordovaWebView. For example, below xml file is used in cordova official site.
This still works until release 4.0.0 ... Now, the CordovaWebView class has changed to an interface. So we can not use like this anymore.
Copy Cordova Android Project to Native Android Application
Now comes the most excited part, we need to copy useful stuff of cordova project to the native android project.
cordova jar
The first and most important thing is that we need a cordova lib. You can download the latest cordova android 4.0.0 package, then create a jar file. Check the cordova offiicial website.
Navigate to the Android package's /framework directory and run ant jar. It creates the Cordova .jar file, formed as /framework/cordova-x.x.x.jar.
After creating the jar file, we need to import it into our Android Studio project. Copy the jar file to libsfolder and add the follow line in build.gradle.
compile files('libs/cordova-4.0.0.jar')
Try to access the class in cordova lib after you finish to see if everything is ok.
www folder
Copy the www folder in cordova project to the android project. Note that the folder structure on the right is for Android Studio.
platforms/android/assets/www -& src/main/assets/www
We have added plugins for cordova project above, so we need to add them to our android project.
We need to use the cordova plugins in folder platforms/android/src/, instead of plugins/, because when you run cordova build, cordova will copy the plugins in folder plugins/ to folderplatforms/android/src/ and perform some magic under the table(the config.xml indeed).
platforms/android/src/plugin_folder -& src/main/java/
config.xml
Cordova use the config.xml for its configuration, likes plugins declarations. Note that do NOT use the file in root path of cordova project, use that in platforms folder instead.
platforms/android/res/xml/config.xml -& src/main/res/xml/
(window.slotbydup=window.slotbydup || []).push({
id: '2467140',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467141',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467142',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467143',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467148',
container: s,
size: '1000,90',
display: 'inlay-fix'ios如何在webview上添加别的视图
的那班车走
为您推荐:
其他类似问题
扫描下载二维码

我要回帖

更多关于 ios webview 布局 的文章

 

随机推荐