欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

实例详解IOS开发之UIWebView

程序员文章站 2023-11-22 08:47:40
ios开发之uiwebview 是本文要介绍的内容,uiwebview是ios sdk中一个最常用的控件。是内置的浏览器控件,我们可以用它来浏览网页、打开文档等等。这篇文章...

ios开发之uiwebview 是本文要介绍的内容,uiwebview是ios sdk中一个最常用的控件。是内置的浏览器控件,我们可以用它来浏览网页、打开文档等等。这篇文章我将使用这个控件,做一个简易的浏览器。如下图:

实例详解IOS开发之UIWebView

我们创建一个window-based application程序命名为:uiwebviewdemo

uiwebview的loadrequest可以用来加载一个url地址,它需要一个nsurlrequest参数。我们定义一个方法用来加载url。在uiwebviewdemoviewcontroller中定义下面方法:

- (void)loadwebpagewithstring:(nsstring*)urlstring{ 
nsurl *url =[nsurl urlwithstring:urlstring]; 
nslog(urlstring); 
nsurlrequest *request =[nsurlrequest requestwithurl:url]; 
[webview loadrequest:request];}

在界面上放置3个控件,一个textfield、一个button、一个uiwebview,布局如下:

实例详解IOS开发之UIWebView

在代码中定义相关的控件:webview用于展示网页、textfield用于地址栏、activityindicatorview用于加载的动画、buttonpress用于按钮的点击事件。

@interface uiwebviewdemoviewcontroller :uiviewcontroller<uiwebviewdelegate> { 
iboutlet uiwebview *webview;
iboutlet uitextfield *textfield;
uiactivityindicatorview *activityindicatorview;
}
- (ibaction)buttonpress:(id) sender;
- (void)loadwebpagewithstring:(nsstring*)urlstring;
@end 

使用ib关联他们。

设置uiwebview,初始化uiactivityindicatorview:

- (void)viewdidload{ 
[super viewdidload]; 
webview.scalespagetofit =yes; 
webview.delegate =self; 
activityindicatorview = [[uiactivityindicatorview alloc] 
initwithframe : cgrectmake(0.0f, 0.0f, 32.0f, 32.0f)] ; 
[activityindicatorview setcenter: self.view.center] ; 
[activityindicatorview setactivityindicatorviewstyle: uiactivityindicatorviewstylewhite] ; 
[self.view addsubview : activityindicatorview] ; 
[self buttonpress:nil]; // do any additional setup after loading the view from its nib.} 

uiwebview主要有下面几个委托方法:

1、- (void)webviewdidstartload:(uiwebview *)webview;开始加载的时候执行该方法。
2、- (void)webviewdidfinishload:(uiwebview *)webview;加载完成的时候执行该方法。
3、- (void)webview:(uiwebview *)webview didfailloadwitherror:(nserror *)error;加载出错的时候执行该方法。

我们可以将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];
}

总结:本文通过实现一个简单的浏览器,说明了uiwebview的方法和属性,相信通过这个例子,应该明白uiwebview的使用了。

后续还会持续给大家分享有关ios开发之uiwebview 的相关知识,敬请关注网站,谢谢。