iOS中UIWebView网页加载组件的基础及使用技巧实例

时间:2022-09-19 18:32:10

基本用法示例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
- (void)viewDidLoad
{
  [super viewDidLoad];
  // Do any additional setup after loading the view.
 
  UIWebView * webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 20, ScreenWidth, ScreenHeight-20)];
  // 自动队页面进行缩放以适应屏幕
  webView.scalesPageToFit = YES;
  webView.userInteractionEnabled = YES;
  webView.opaque = YES;
 
  [self.view addSubview:webView];
 
  NSURL * url = [NSURL URLWithString:@"http://www.youku.com"];
  NSURLRequest * request = [NSURLRequest requestWithURL:url];
  [webView loadRequest:request];
//  NSString * myHT = @"优酷";
//  [webView loadHTMLString:myHT baseURL:url];
/*
  [webView goBack];    // 返回
  [webView goForward];   // 前往
  [webView reload];
  [webView stopLoading];
 */
  webView.delegate = self;
 
  //移除滚动后的外边阴影
  UIScrollView *scrollView = webView.scrollView;
  for (int i = 0; i < scrollView.subviews.count ; i++) {
    UIView *view = [scrollView.subviews objectAtIndex:i];
    if ([view isKindOfClass:[UIImageView class]]) {
      view.hidden = YES ;
    }
  }
}
 
#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
 
  /**
   * typedef NS_ENUM(NSInteger, UIWebViewNavigationType) {
   * UIWebViewNavigationTypeLinkClicked,
   * UIWebViewNavigationTypeFormSubmitted,
   * UIWebViewNavigationTypeBackForward,
   * UIWebViewNavigationTypeReload,
   * UIWebViewNavigationTypeFormResubmitted,
   * UIWebViewNavigationTypeOther
   };
   */
 
  NSLOG_FUNCTION;
 
  return YES;
}
 
// 开始加载
- (void)webViewDidStartLoad:(UIWebView *)webView{
 
  NSLOG_FUNCTION;
 
}
 
// 完成加载
- (void)webViewDidFinishLoad:(UIWebView *)webView{
 
  NSLOG_FUNCTION;
 
}
 
// 加载失败,弹出错误提示
- (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];
  NSLOG_FUNCTION;
 
}


以下是关于它的一些使用技巧:

1.让网页适应手机屏幕宽度

如果用UIWebView显示一些pc站的网页,会发现网页会超出屏幕,显得很不好看,这时可以在webViewDidFinishLoad这个代理里面通过js添加一个meta:

?
1
2
3
4
5
6
7
8
9
- (void)webViewDidFinishLoad:(UIWebView *)webView
 
{
 
  NSString *meta = [NSString stringWithFormat:@"document.getElementsByName(\"viewport\")[0].content = \"width=%f, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"", IPHONE_WIDTH];
 
  [webView stringByEvaluatingJavaScriptFromString:meta];
 
}

注意:使用这个方法时要把UIWebView的scalesPageToFit设成NO

?
1
webView.scalesPageToFit = NO;

 

2.为网页中的图片添加点击事件,当点击图片时放大查看

思路是给每一个img标签添加onclick事件,在事件中把img的src属性封装成一个特殊的url,然后进行拦截

如果是通过loadHTMLString去加载网页的话,可以执行下面一句进行替换:

 

复制代码 代码如下:

 

    html = [html stringByReplacingOccurrencesOfString:@"<img " withString:@"<img onclick=\"window.location.href=('http://src.'+this.src);\" "];

 

 

如果是通过loadRequest,那就要再webViewDidFinishLoad中执行以下JS:

?
1
2
3
4
5
6
7
8
9
10
11
NSString *js = @"var imgs = document.getElementsByTagName(\"img\");"
 
"for(var i=0;i<imgs.length;i++){"
 
"  var img = imgs[i];"
 
"  img.onclick=function(){window.location.href=('http://src.'+this.src);}"
 
"}";
 
[webView stringByEvaluatingJavaScriptFromString:js];

然后通过webview的代理方法去拦截,拿到图片的url,之后就可以做各种处理了

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
 
{
 
  NSString *url = request.URL.absoluteString;
 
  if ([url hasPrefix:@"http://src."])
 
  {
 
    url = [url stringByReplacingOccurrencesOfString:@"http://src." withString:@""];
 
    // Do something..
 
    return NO;
 
  }
 
  return YES;
 
}

3.为UIWebView添加一个跟随网页滚动的页头

UIWebView里包含一个scrollview,可以向scrollview里添加一个页头以达到跟随网页滚动的效果

?
1
2
3
4
5
6
7
8
9
10
11
12
13
CGFloat headerHeight = 36.0f;
 
// 注意:y坐标必须是负数,IPHONE_WIDTH是屏幕宽度
 
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, -headerHeight, IPHONE_WIDTH, headerHeight)];
 
[_webView.scrollView addSubview:_headerView];
 
// 修改webView的scrollView的contentInset,让顶部留出一点空间
 
UIEdgeInsets edgeInset = _webView.scrollView.contentInset;
 
_webView.scrollView.contentInset = UIEdgeInsetsMake(headerView.frameHeight, edgeInset.left, edgeInset.bottom, edgeInset.right);