UIWebView的使用

UIWebView的使用

技术杂谈小彩虹2021-07-16 4:36:3870A+A-
WebView的几种使用方法:

首先:配置Plist文件 可以进行网络请求

Property Plist 或者:Source Code写入HTML格式

Source Code

否则:你懂得~~

未配置Plist文件,请求失败

使用StoryBoard拖3个WebView,平分了整个屏幕:

StoryBoard创建好界面 再把背景色设置为紫色。 三个WebView:

@property (strong, nonatomic) IBOutlet UIWebView *webV_1;
@property (strong, nonatomic) IBOutlet UIWebView *webV_2;
@property (strong, nonatomic) IBOutlet UIWebView *webV_3;

获取本地文件内容(HTML文件)

创建本地HTML文件

创建本地文件

创建、命名

在“MyCreateFile.html”本地文件,编辑HTML格式的内容:

  <html>
      <meta charset="UTF-8">
          <head lang="en">
              <meta charset="UTF-8">
                  <h1 style='color:blue'>
                      What's The Fox say?
                  </h1>
          </head>
    
          <br>  </br>
    
          <body>
              <h1>What's The Fox say?</h1>   <!-- 一级标题  -->
              <h2>我的HTML标题Lev2</h2>
              <h3>我的HTML标题Lev3</h3>
              <h4>我的HTML标题Lev4</h4>
              <h5>我的HTML标题Lev5</h5>
              <h6>我的HTML标题Lev6</h6>    <!-- 六级标题  -->
              <p>
              <p style='color:red'>           <!--  颜色改变  -->
              老子的HTML学习第一次
              </p>
        
              <p>
              劳资的HTML学习第一次 What's The Fox says
              劳资HTML学习第一次  劳资HTML学习第一次
              劳资HTML学习第一次劳资HTML学习第一次
              </p>

              <input type="button" value="按钮">
              <input type = "color">  <br/>          <!--  <br/>:自动换行  -->
              <!--   <br />=<br>...</br>  -->
              <input type = "text" placeholder="请输入账号">    <br/>
                    
              <a href="https://www.baidu.com">百度一下,你就上当
              </a>
            
              <form>
              <input type='checkbox' name='sex' value='male' selected=selected>程序员
              <input type='checkbox' name='sex' value='male' selected=selected>老板 <br/>     <!--  checkbox:多选框  -->
              <input type='radio' name='sex' value='male' selected=selected>男人
              <input type='radio' name='sex' value='female'>女人                              <!--  radio:单选框  -->
              </form>
          </body>
  </html>

在 - (void)viewDidLoad { }里面:

[self loadLocalHtml];

-(void)loadLocalHtml
{
  //1.从本地获取HTML文件
  NSString * path = [[NSBundle mainBundle] pathForResource:@"MyCreateFile" ofType:@"html"];

  //2.从文件中获取HTML字符串
  NSString * htmlStr = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

  //3.加载在webview中
  [self.webV_1 loadHTMLString:htmlStr baseURL:nil];


  //4.可以 加载在Label的富文本中    (但是只能观看~)
  //NSData * data = [htmlStr dataUsingEncoding:NSUTF8StringEncoding];   //Label的字体 大小 并不能影响 html字体的大小
  //NSAttributedString * str = [[NSAttributedString alloc] initWithData:data options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
  //self.htmlLB.attributedText = str;

}

其中:

[self.webV_1 loadHTMLString:htmlStr baseURL:nil];

对于“[ loadHTMLString: baseURL: ]”方法,可以替换为:

NSURL * webURL = [NSURL fileURLWithPath:path];  //通过文件路径字符串获取URL
NSURLRequest * URLRequest = [NSURLRequest requestWithURL:webURL];//设置请求 提交的相关URL
[self.webV_1 loadRequest:URLRequest];          //提交请求

好处:URL(统一资源定位符~~)不但可以获取本地文件内容,也可以加载网络信息。 当然“[ loadHTMLString: baseURL: ]”方法可以加载HTML格式CSS格式的网络信息! 之前自己只是将网络上请求的信息(CSS格式)加载出来了而已!

之前处理 网络请求到的CCS格式的信息

网上说法:baseURL如果是一个网络路径,就能加载 网络上的CSS信息了!但是自己还没试过。。。。。 希望明白的朋友指点一下~ !

苹果官方 不推荐用来加载网络信息:( 当然有时候 官方就是屁~) “ - loadHTMLString:baseURL: ”方法

“ - loadRequest: ”方法

加载的效果:

本地HTML文件加载  展示效果

总结:

1.“<head></head>”部分 只有一个蓝色标题。
2.“<br><br/>”效果与“<br/> ”相同 (换行操作)。
3.“程序员”、“老板” 为多选项;“男人”、“女人” 为单选项。
4.点击“百度一下,你就上当”,进入百度网页。
※5.WebView的背景色跟UIScrollView一样(包含了一个UIScrollView属性),蓝色会被内容视图遮挡。


从服务器加载 HTML页面

在 - (void)viewDidLoad { }里面:

[self loadInternetHtml];

//从服务器加载HTML页面
-(void)loadInternetHtml
{
   //加载服务器HTML页面的 模式
   // NSString *urlStr = [NSString stringWithFormat:@"%@/appservice/getAnnouncementDetail.do?id=%@",O2O_URL,self.idStr]; 
    NSString *urlStr = @"https://www.baidu.com";
    NSURL *url = [NSURL URLWithString:urlStr];
    NSLog(@"url:%@",url);
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webV_1 loadRequest:request];

}

加载的效果:直接跳转到所需要的页面

直接跳转到 所需要展示的页面

使用WebView的delegate方法:
@interface ViewController () <UIWebViewDelegate> //  设置代理

在 - (void)viewDidLoad { }里面:

[self useWebViewDelegate];

-(void)useWebViewDelegate
{
    self.webV_2.delegate = self;        // 设置代理    
    self.webV_2.scrollView.bounces = NO;//禁止WebView的弹簧效果

    NSString *urlStr = @"https://www.baidu.com";
    NSURL *url = [NSURL URLWithString:urlStr];
    NSLog(@"url:%@",url);
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    [self.webV_2 loadRequest:request];
}

代理里面的方法:

#pragma mark - UIWebView Delegate
- (void)webViewDidStartLoad:(UIWebView *)webView 
{ 开始加载时调用的方法
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error 
{加载失败时调用的方法

}


// 禁止webview中的链接点击   (用于 :过滤 请求条件)
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{   // 页面准备加载内容时调用,通过返回值来进行判断是否要加载
    if (webView == self.webV_2) {   // 是第二个WebView
        if(navigationType == UIWebViewNavigationTypeLinkClicked) 
       { //判断点击的是否为 链接        
            return NO;    //返回“NO”,不加载到链接的页面
        }else{
            return YES;
        }
    } else { // 其他WebView可以响应 链接
        return YES;
    }
}

加载效果: 第二个WebView每次点击到响应的类型,都会判断是否为“链接”类型:如果是,不予响应(进入链接页面)。

如果点击的 是链接类型,不予响应

-(void)webViewDidFinishLoad:(UIWebView *)webView
{   // 加载完后触发
    if (webView == self.webV_2) {   // 是第二个WebView
        NSString * fontStr = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '50%'";//字体大小
        // ………………

        [self.webV_2 stringByEvaluatingJavaScriptFromString:fontStr];
    }

}

加载效果:

第二个WebView的字体,缩小为原来的50%


JavaScript方式,操作web数据

需要等UIWebView中的页面加载完成之后去调用。 “ - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;”方法向UIWebView传递一段需要执行的JavaScript代码,最后获取执行结果。 在 - (void)viewDidLoad { }里面:

[self useJavaScriptWay];

-(void)useJavaScriptWay {
    self.webV_3.delegate = self;        //设置代理

    NSURL *url =[[NSURL alloc] initWithString:@"https://www.baidu.com"];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    [self.webV_3 loadRequest:request];    
}

在页面加载完成后,去调用WebView的“stringByEvaluatingJavaScriptFromString”方法:

-(void)webViewDidFinishLoad:(UIWebView *)webView
{   // 加载完后触发
    if (webView == self.webV_3) {
        [self changeValueForUsingJavaScriptWay];
    }
}

-(void)changeValueForUsingJavaScriptWay {
    // 获取当前页面的URL
    NSString *currentURL = [self.webV_3 stringByEvaluatingJavaScriptFromString:@"document.location.href"];
    //获取当前页面的标题名称
    NSString *title = [self.webV_3 stringByEvaluatingJavaScriptFromString:@"document.title"];
    NSLog(@"%URL:@====title:%@",currentURL,title);
   




    // 交互格式
    //[self.webV_3 stringByEvaluatingJavaScriptFromString:@"方法名(%@)",参数] ];


    //插入js代码
    //[self.webV_3 stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
    //"script.type = 'text/javascript';"
    //"script.text = \"function myFunction() { "
    //"var field = document.getElementsByName('q')[0];"
    //"field.value='goyoholBest.com';"
    //"document.forms[0].submit();"
    //"}\";"
    //"document.getElementsByTagName('head')[0].appendChild(script);"];


    //给网页增加utf-8编码
    //[self.webV_3 stringByEvaluatingJavaScriptFromString:
    //@"var tagHead =document.documentElement.firstChild;"
    //"var tagMeta = document.createElement(\"meta\");"
    //"tagMeta.setAttribute(\"http-equiv\", \"Content-Type\");"
    //"tagMeta.setAttribute(\"content\", \"text/html; charset=utf-8\");"
    //"var tagHeadAdd = tagHead.appendChild(tagMeta);"];


    //给网页增加css样式
    //[self.webV_3 stringByEvaluatingJavaScriptFromString:
    //@"var tagHead =document.documentElement.firstChild;"
    //"var tagStyle = document.createElement(\"style\");"
    //"tagStyle.setAttribute(\"type\", \"text/css\");"
    //"tagStyle.appendChild(document.createTextNode(\"BODY{padding: 20pt 15pt}\"));"
    //"var tagHeadAdd = tagHead.appendChild(tagStyle);"];

    //拦截网页图片  并修改图片大小
    [self.webV_3 stringByEvaluatingJavaScriptFromString:
    @"var script = document.createElement('script');"
    "script.type = 'text/javascript';"
    "script.text = \"function ResizeImages() { "
    "var myimg,oldwidth;"
    "var maxwidth=50;" //缩放系数
    "for(i=0;i <document.images.length;i++){"
    "myimg = document.images[i];"
    "if(myimg.width > maxwidth){"
    "oldwidth = myimg.width;"
    "myimg.width = maxwidth;"
    "myimg.height = myimg.height * (maxwidth/oldwidth);"
    "}"
    "}"
    "}\";"
    "document.getElementsByTagName('head')[0].appendChild(script);"];
    [self.webV_3 stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
  }

加载的效果: 图片被缩小 及 进入一个页面打印其URL及title信息 图片被缩小

控制台打印结果:

    2016-12-26 01:39:52.008 WebViewUse-Demo[3221:164983] https://www.baidu.com/====百度一下
    2016-12-26 01:39:58.571 WebViewUse-Demo[3221:164983] https://www.baidu.com/#iact=wiseindex%2Ftabs%2Fnews%2Factivity%2Fnewsdetail%3D%257B%2522linkData%2522%253A%257B%2522name%2522%253A%2522iframe%252Fmib-iframe%2522%252C%2522id%2522%253A%2522feed%2522%252C%2522index%2522%253A0%252C%2522url%2522%253A%2522https%253A%252F%252Fm.baidu.com%252Ffeed%252Fdata%252Flandingpage%253Fnid%253D3286129817483816749%2526n_type%253D1%2526p_from%253D2%2522%252C%2522title%2522%253A%2522%25E7%2588%25B1%25E7%25BE%258E%25E5%25B0%25B1%25E8%25A6%2581%25E7%2598%25A6%25E7%2598%25A6%25E7%2598%25A6%2522%257D%257D====百度一下
    2016-12-26 01:39:59.196 WebViewUse-Demo[3221:164983] https://www.baidu.com/#iact=wiseindex%2Ftabs%2Fnews%2Factivity%2Fnewsdetail%3D%257B%2522linkData%2522%253A%257B%2522name%2522%253A%2522iframe%252Fmib-iframe%2522%252C%2522id%2522%253A%2522feed%2522%252C%2522index%2522%253A0%252C%2522url%2522%253A%2522https%253A%252F%252Fm.baidu.com%252Ffeed%252Fdata%252Flandingpage%253Fnid%253D3286129817483816749%2526n_type%253D1%2526p_from%253D2%2522%252C%2522title%2522%253A%2522%25E7%2588%25B1%25E7%25BE%258E%25E5%25B0%25B1%25E8%25A6%2581%25E7%2598%25A6%25E7%2598%25A6%25E7%2598%25A6%2522%257D%257D====百度一下
    2016-12-26 01:40:11.736 WebViewUse-Demo[3221:164983] https://www.baidu.com/#iact=wiseindex%2Ftabs%2Fnews%2Factivity%2Fnewsdetail%3D%257B%2522linkData%2522%253A%257B%2522name%2522%253A%2522iframe%252Fmib-iframe%2522%252C%2522id%2522%253A%2522feed%2522%252C%2522index%2522%253A0%252C%2522url%2522%253A%2522https%253A%252F%252Fm.baidu.com%252Ffeed%252Fdata%252Flandingpage%253Fdsp%253Dwise%2526nid%253D3267967319825678069%2526n_type%253D1%2526p_from%253D3%2522%257D%257D====百度一下
    2016-12-26 01:40:12.039 WebViewUse-Demo[3221:164983] https://www.baidu.com/#iact=wiseindex%2Ftabs%2Fnews%2Factivity%2Fnewsdetail%3D%257B%2522linkData%2522%253A%257B%2522name%2522%253A%2522iframe%252Fmib-iframe%2522%252C%2522id%2522%253A%2522feed%2522%252C%2522index%2522%253A0%252C%2522url%2522%253A%2522https%253A%252F%252Fm.baidu.com%252Ffeed%252Fdata%252Flandingpage%253Fdsp%253Dwise%2526nid%253D3267967319825678069%2526n_type%253D1%2526p_from%253D3%2522%257D%257D====百度一下
    2016-12-26 01:41:11.831 WebViewUse-Demo[3221:164983] https://www.baidu.com/#iact=wiseindex%2Ftabs%2Fnews%2Factivity%2Fnewsdetail%3D%257B%2522linkData%2522%253A%257B%2522name%2522%253A%2522iframe%252Fmib-iframe%2522%252C%2522id%2522%253A%2522feed%2522%252C%2522index%2522%253A0%252C%2522url%2522%253A%2522https%253A%252F%252Fm.baidu.com%252Ffeed%252Fdata%252Flandingpage%253Fnid%253D3286129817483816749%2526n_type%253D1%2526p_from%253D2%2522%252C%2522title%2522%253A%2522%25E7%2588%25B1%25E7%25BE%258E%25E5%25B0%25B1%25E8%25A6%2581%25E7%2598%25A6%25E7%2598%25A6%25E7%2598%25A6%2522%257D%257D====百度一下
    2016-12-26 01:41:12.409 WebViewUse-Demo[3221:164983] https://www.baidu.com/#iact=wiseindex%2Ftabs%2Fnews%2Factivity%2Fnewsdetail%3D%257B%2522linkData%2522%253A%257B%2522name%2522%253A%2522iframe%252Fmib-iframe%2522%252C%2522id%2522%253A%2522feed%2522%252C%2522index%2522%253A0%252C%2522url%2522%253A%2522https%253A%252F%252Fm.baidu.com%252Ffeed%252Fdata%252Flandingpage%253Fnid%253D3286129817483816749%2526n_type%253D1%2526p_from%253D2%2522%252C%2522title%2522%253A%2522%25E7%2588%25B1%25E7%25BE%258E%25E5%25B0%25B1%25E8%25A6%2581%25E7%2598%25A6%25E7%2598%25A6%25E7%2598%25A6%2522%257D%257D====百度一下
    2016-12-26 01:41:13.252 WebViewUse-Demo[3221:164983] https://www.baidu.com/#iact=wiseindex%2Ftabs%2Fnews%2Factivity%2Fnewsdetail%3D%257B%2522linkData%2522%253A%257B%2522name%2522%253A%2522iframe%252Fmib-iframe%2522%252C%2522id%2522%253A%2522feed%2522%252C%2522index%2522%253A0%252C%2522url%2522%253A%2522https%253A%252F%252Fm.baidu.com%252Ffeed%252Fdata%252Flandingpage%253Fnid%253D3286129817483816749%2526n_type%253D1%2526p_from%253D2%2522%252C%2522title%2522%253A%2522%25E7%2588%25B1%25E7%25BE%258E%25E5%25B0%25B1%25E8%25A6%2581%25E7%2598%25A6%25E7%2598%25A6%25E7%2598%25A6%2522%257D%257D====百度一下
    2016-12-26 01:41:13.599 WebViewUse-Demo[3221:164983] https://www.baidu.com/#iact=wiseindex%2Ftabs%2Fnews%2Factivity%2Fnewsdetail%3D%257B%2522linkData%2522%253A%257B%2522name%2522%253A%2522iframe%252Fmib-iframe%2522%252C%2522id%2522%253A%2522feed%2522%252C%2522index%2522%253A0%252C%2522url%2522%253A%2522https%253A%252F%252Fm.baidu.com%252Ffeed%252Fdata%252Flandingpage%253Fnid%253D3286129817483816749%2526n_type%253D1%2526p_from%253D2%2522%252C%2522title%2522%253A%2522%25E7%2588%25B1%25E7%25BE%258E%25E5%25B0%25B1%25E8%25A6%2581%25E7%2598%25A6%25E7%2598%25A6%25E7%2598%25A6%2522%257D%257D====百度一下

我现在看到“百度”,就

Tips:

使用较少的方法,也更自由:

  - (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL;

其中:data是文件数据,MIMEType是文件类型,textEncodingName是编码类型,baseURL是素材资源路径。 属性和变量:

  @property (nonatomic,readonly,retain)UIScrollView *scrollView; // 内置的scrollView
  @property (nonatomic,readonly,retain)NSURLRequest *request;    // URL请求

  @property (nonatomic,readonly,getter=canGoBack)BOOL canGoBack;        // 获取能否返回上一级
  @property (nonatomic,readonly,getter=canGoForward)BOOL canGoForward;  // 获取能否跳转下一级
  @property (nonatomic,readonly,getter=isLoading)BOOL loading;          // 获取是否 正在加载数据

  @property (nonatomic)UIDataDetectorTypes dataDetectorTypesNS_AVAILABLE_IOS(3_0);  // 设置某些数据变为链接形式,这个枚举可以设置如电话号,地址,邮箱等转化为链接
  @property (nonatomic)BOOL allowsInlineMediaPlaybackNS_AVAILABLE_IOS(4_0);         // 设置是否使用内联播放器播放视频
  @property (nonatomic)BOOL mediaPlaybackRequiresUserActionNS_AVAILABLE_IOS(4_0);   // 设置视频是否自动播放
  @property (nonatomic)BOOL mediaPlaybackAllowsAirPlayNS_AVAILABLE_IOS(5_0);        // 设置音频播放是否支持AirPlay功能
  @property (nonatomic)BOOL suppressesIncrementalRenderingNS_AVAILABLE_IOS(6_0);    // 设置是否将数据加载如内存后渲染界面
  @property (nonatomic)BOOL keyboardDisplayRequiresUserActionNS_AVAILABLE_IOS(6_0); // 设置用户交互模式

以下是iOS7之后才有的属性:

  @property (nonatomic)UIWebPaginationMode paginationModeNS_AVAILABLE_IOS(7_0);

此属性是用来设置一种模式,当网页大小超出view时,可将网页设置成以“翻页”的效果展示,枚举如下:

  typedef NS_ENUM(NSInteger, UIWebPaginationMode) {
          UIWebPaginationModeUnpaginated,  // 不使用翻页效果
          UIWebPaginationModeLeftToRight,  // 将网页超出部分分页,从左向右进行翻页
          UIWebPaginationModeTopToBottom,  // 将网页超出部分分页,从上向下进行翻页
          UIWebPaginationModeBottomToTop,  // 将网页超出部分分页,从下向上进行翻页
          UIWebPaginationModeRightToLeft   // 将网页超出部分分页,从右向左进行翻页
  };


  @property (nonatomic)CGFloat pageLengthNS_AVAILABLE_IOS(7_0);            // 设置每一页的长度
  @property (nonatomic)CGFloat gapBetweenPagesNS_AVAILABLE_IOS(7_0);       // 设置每一页的间距
  @property (nonatomic,readonly)NSUInteger pageCountNS_AVAILABLE_IOS(7_0); // 获取分页数

酌情调用以下方法:

  - (void)reload;       // 重新加载数据
  - (void)stopLoading;  // 停止加载数据

  - (void)goBack;       // 返回上一级
  - (void)goForward;    // 跳转下一级

暂时就说这么多吧!!之后还会写一篇JS交互的文章~ 也不知道什么时候了~~ ?哈哈

goyohol's essay

点击这里复制本文地址 以上内容由权冠洲的博客整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!

支持Ctrl+Enter提交

联系我们| 本站介绍| 留言建议 | 交换友链 | 域名展示
本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除

权冠洲的博客 © All Rights Reserved.  Copyright quanguanzhou.top All Rights Reserved
苏公网安备 32030302000848号   苏ICP备20033101号-1

联系我们