UIWebView 初学者快速入门(实现自己的第一个网页)3

1.创建根视图,并添加 UIWebView 属性,并设置好代理
@interface RootViewController () < UIWebViewDelegate >{
   
   
UIWebView *_webView;

}
2.创建网页视图
/* 添加 网页视图 */
   _webView = [[UIWebViewalloc]initWithFrame:CGRectMake(0,_searchBar.frame.size.height + kHEIGHT_TITLE,
               self.view.bounds.size.width, self.view.bounds.size.height - _toolbar.frame.size.height - _searchBar.frame.size.height - kHEIGHT_TITLE)];
   
   
// 数据检测,例如内容中有邮件地址,点击之后可以打开邮件软件编写邮件
   _webView.dataDetectorTypes =UIDataDetectorTypeAll;
    _webView . delegate = self ;
         //设置网页地址,需要注意,设置网页地址需要在前面添加上 http://   不然是找不到网页的
    NSURLRequest *request = [ NSURLRequest requestWithURL :[ NSURL URLWithString : @"http://www.sankai.com" ]];
    [
self . view addSubview : _webView ];
    [_webViewloadRequest:request];
3.这时候我们就应该能看到具体的网页了,但是我们有哪些时机可以进行操作呢?
//开始加载请求时调用,每次页面发生改变都会调用这个方法
- ( BOOL )webView:( UIWebView *)webView shouldStartLoadWithRequest:( NSURLRequest *)request navigationType:( UIWebViewNavigationType )navigationType;
//页面开始加载
- (void)webViewDidStartLoad:(UIWebView *)webView;
//页面结束加载
- ( void )webViewDidFinishLoad:( UIWebView *)webView;
//页面请求失败
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullableNSError *)error;
4.知道了这四个时机,我们也就可以对程序操作进行一些基础的操作了.首先要做到的就是,当我们的程序正在请求页面的时候,怎么展示出我们的页面当前正在加载当中呢?
方案一:
// 开始加载
- (
void )webViewDidStartLoad:( UIWebView *)webView{
   
// 显示网络请求加载
    [UIApplicationsharedApplication].networkActivityIndicatorVisible=true;
}
// 结束加载
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    // 隐藏网络请求加载图标
    [
UIApplication sharedApplication ]. networkActivityIndicatorVisible = false ;
   
// 设置按钮状态
    [
self setBarButtonStatus ];
}
// 加载失败
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullableNSError *)error{
    NSLog ( @"error detail:%@" ,error. localizedDescription );
   UIAlertView *alert=[[UIAlertViewalloc]initWithTitle:@"系统提示"message:@"网络连接发生错误!"delegate:selfcancelButtonTitle:nil                
                         otherButtonTitles:@"确定",nil];
    [alert show ];
}
实现效果:

方案二:
重新生成一个属性
@interface RootViewController () < UIWebViewDelegate , UISearchBarDelegate >{
    UIWebView *_webView;
   UIActivityIndicatorView *_activityIndicator;
}
// 开始加载
- (void)webViewDidStartLoad:(UIWebView *)webView{
    // 创建 UIActivityIndicatorView 背底半透明 View
   
UIView *view = [[ UIView alloc ] initWithFrame :[ UIScreen mainScreen ]. bounds ];
    [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 ];
}
// 结束加载
- (
void )webViewDidFinishLoad:( UIWebView *)webView{
    [
_activityIndicator stopAnimating ];
   
UIView *view = ( UIView *)[ self . view viewWithTag : 108 ];
    [viewremoveFromSuperview];
}
// 加载失败
- (
void )webView:( UIWebView *)webView didFailLoadWithError:( nullable NSError *)error{
    [
_activityIndicator stopAnimating ];
   
UIView *view = ( UIView *)[ self . view viewWithTag : 108 ];
    [viewremoveFromSuperview];
}
实现效果:

5.这时候我们已经让页面在等待的时候不能点击了,那我们如何实现自己输入网址呢?
重新生成几个属性
@interface RootViewController () < UIWebViewDelegate , UISearchBarDelegate >{
   
   
UIWebView *_webView;
   
UIActivityIndicatorView *_activityIndicator;
   
   
UIToolbar *_toolbar;
   
UISearchBar *_searchBar;
   
UIBarButtonItem *_barButtonBack;
   
UIBarButtonItem *_barButtonForward;
}
在 ViewDidLoad 中设置新的 View,记得添加在 WebView 的上方.
    /* 添加地址栏 */
   
_searchBar =[[ UISearchBar alloc ] initWithFrame : CGRectMake ( 0 , kHEIGHT_TITLE , self . view . bounds . size . width , 44 )];
   
_searchBar . delegate = self ;
    [
self . view addSubview : _searchBar ];
   
   
   
/* 添加下方工具栏 */
   
_toolbar =[[ UIToolbar alloc ] initWithFrame : CGRectMake ( 0 , self . view . bounds . size . height - 44 , self . view . bounds . size . width , 44 )];
   
UIButton *btnBack=[ UIButton buttonWithType : UIButtonTypeSystem ];
    btnBack.
bounds = CGRectMake ( 0 , 0 , 50 , 32 );
   
//    [btnBack setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
   
//    [btnBack setImage:[UIImage imageNamed:@"back_disable.png"] forState:UIControlStateDisabled];
    [btnBack
setTitle : @" 后退 " forState :( UIControlStateNormal )];
    [btnBack
addTarget : self action : @selector (webViewBack) forControlEvents : UIControlEventTouchUpInside ];
   
_barButtonBack =[[ UIBarButtonItem alloc ] initWithCustomView :btnBack];
   
_barButtonBack . enabled = NO ;
   
   
// 设置一个空白的区域 , 用于自动调节按钮间的间距
   
UIBarButtonItem *btnSpacing=[[ UIBarButtonItem alloc ] initWithBarButtonSystemItem : UIBarButtonSystemItemFlexibleSpace target : nil action : nil ];
   
   
UIButton *btnForward=[ UIButton buttonWithType : UIButtonTypeSystem ];
    btnForward.
bounds = CGRectMake ( 0 , 0 , 50 , 32 );
   
//    [btnForward setImage:[UIImage imageNamed:@"forward.png"] forState:UIControlStateNormal];
   
//    [btnForward setImage:[UIImage imageNamed:@"forward_disable.png"] forState:UIControlStateDisabled];
    [btnForward
setTitle : @" 前进 " forState :( UIControlStateNormal )];
    [btnForward
addTarget : self action : @selector (webViewForward) forControlEvents : UIControlEventTouchUpInside ];
   
_barButtonForward =[[ UIBarButtonItem alloc ] initWithCustomView :btnForward];
   
_barButtonForward . enabled = NO ;
   
   
_toolbar . items = @[ _barButtonBack ,btnSpacing, _barButtonForward ] ;
    [self.viewaddSubview:_toolbar];
并实现 Button 的代理事件
#pragma mark 设置前进后退按钮状态
-( void )setBarButtonStatus{
   
if ( _webView . canGoBack ) {
       
_barButtonBack . enabled = YES ;
    }
else {
       
_barButtonBack . enabled = NO ;
    }
   
if ( _webView . canGoForward ){
       
_barButtonForward . enabled = YES ;
    }
else {
       
_barButtonForward . enabled = NO ;
    }
}
#pragma mark 后退
-( void )webViewBack{
    [
_webView goBack ];
}
#pragma mark 前进
-( void )webViewForward{
    [
_webView goForward ];
}
实现完Button 的代理,还有 SearchBar代理方法
#pragma mark 点击搜索按钮或回车
-( void )searchBarSearchButtonClicked:( UISearchBar *)searchBar{
    [
self request : _searchBar . text ];
}
在这里进行了一个判断,如果你填写的信息是 file 开头,也就是本地文件,就去加载本地,如果是 http 开头,就去跳转到输入网页,如果都不是,就用过百度去搜索.
#define kFILEPROTOCOL @ "file://"
#pragma mark 浏览器请求
-( void )request:( NSString *)urlStr{
   
// 创建 url
   
NSURL *url;
   
   
// 如果 file:// 开头的字符串则加载 bundle 中的文件
   
if ([urlStr hasPrefix : kFILEPROTOCOL ]){
       
// 取得文件名
       
NSRange range= [urlStr rangeOfString : kFILEPROTOCOL ];
       
NSString *fileName=[urlStr substringFromIndex :range. length ];
        url=[[
NSBundle mainBundle ] URLForResource :fileName withExtension : nil ];
    }
else if (urlStr. length > 0 ){
       
// 如果是 http 请求则直接打开网站
       
if ([urlStr hasPrefix : @"http" ]) {
            url=[
NSURL URLWithString :urlStr];
        }
else { // 如果不符合任何协议则进行搜索
            urlStr=[
NSString stringWithFormat : @"http://www.baidu.com/s?wd=%@" ,urlStr];
        }
        urlStr=[urlStr
stringByAddingPercentEscapesUsingEncoding : NSUTF8StringEncoding ]; //url 编码
        url=[
NSURL URLWithString :urlStr];
       
    }
   
   
// 创建请求
   
NSURLRequest *request=[ NSURLRequest requestWithURL :url];
   
   
// 加载请求页面
    [
_webView loadRequest :request];
}


更多精彩文章,尽在我的公众号.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值