当前位置:首页 > 通信资讯 > 正文

iOS开发实战(ios开发基础)

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

iOS开发实战(ios开发基础)

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

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

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

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

iOS开发实战(ios开发基础)

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

?
1 2 3 4 5 6 7 8 @interface uiwebviewdemoviewcontroller :uiviewcontroller<uiwebviewdelegate> { iboutlet uiwebview *webview; iboutlet uitextfield *textfield; uiactivityindicatorview *activityindicatorview; } - (ibaction)buttonpress:(id) sender; - (void)loadwebpagewithstring:(nsstring*)urlstring; @end

使用ib关联他们。

设置uiwebview,初始化uiactivityindicatorview:

?
1 2 3 4 5 6 7 8 9 10 - (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放置到前面两个委托方法中。

?
1 - (void)webviewdidstartload:(uiwebview *)webview{ [activityindicatorview startanimating] ;}- (void)webviewdidfinishload:(uiwebview *)webview{ [activityindicatorview stopanimating];}

buttonpress方法很简单,调用我们开始定义好的loadwebpagewithstring方法就行了:

?
1 2 3 4 5 - (ibaction)buttonpress:(id) sender { [textfield resignfirstresponder]; [self loadwebpagewithstring:textfield.text]; }

当请求页面出现错误的时候,我们给予提示:

?
1 2 3 4 5 6 - (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 的相关知识,敬请关注服务器之家网站,谢谢。

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。