31、[ iOS ] UIWebView 使用详解

1、初始化,实现代理 UIWebViewDelegate

@property (nonatomic ,strong) UIWebView *urlWebView;
    self.urlWebView     = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.urlWebView .delegate = self;//设置代理
    self.urlWebView .scalesPageToFit = YES;//自动对页面进行缩放以适应屏幕
    self.urlWebView .scrollView.bouncesZoom = NO; //不能拖动
    self.urlWebView .dataDetectorTypes = UIDataDetectorTypePhoneNumber;//自动检测网页上的电话号码,单击可以拨打
  
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://baidu.com"]];
    [urlWebView loadRequest:request];//加载网页
    
    [self.view addSubview:self.urlWebView ];

2、代理方法

// ------开始请求
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    return YES;
}
// ------开始加载
- (void)webViewDidStartLoad:(UIWebView *)webView {
  
}
// ------结束加载
- (void)webViewDidFinishLoad:(UIWebView *)webView {

}
// ------请求失败
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    
}

3、常用方法,一般写在webViewDidFinishLoad方法里

// ------获取当前网页全部图片URL
NSString *imageUrls = [self.urlWebView stringByEvaluatingJavaScriptFromString:@"var str=new Array();"
                               "$('img').each(function(){str.push($(this).attr('src'));});"
                               "str.join(',');"];
// ------获取当前网页第一张图片URL
NSString *firstImageUrl = [self.urlWebView stringByEvaluatingJavaScriptFromString:@"var images = document.getElementsByTagName('img');images[0].src.toString();"];

// ------获取当前网页title
NSString *currentTitle = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];

// ------获取当前网页URL
NSString *currentURL = webView.request.URL.absoluteString;

// ------获取当前网页的html
NSString *lJs = @"document.documentElement.innerHTML";
NSString *currentHTML = [webView stringByEvaluatingJavaScriptFromString:lJs];

// ------网页缩放
[webView stringByEvaluatingJavaScriptFromString:@"document.body.style.zoom = 2.0"];   //2.0为缩放倍数

4、自定义按钮常用方法

// ------加载
[self.urlWebView reload];
// ------停止加载
[self.urlWebView stopLoading];
// ------返回
[self.urlWebView goBack];
// ------前进
[self.urlWebView goForward];

你可能感兴趣的:(31、[ iOS ] UIWebView 使用详解)