欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

iOS中UIWebview中网页宽度自适应的问题,iosuiwebview

来源: 开发者 投稿于  被查看 24681 次 评论:20

iOS中UIWebview中网页宽度自适应的问题,iosuiwebview


有的网页中会使用"<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">"这个标签来设置网页的宽度,不过带来的问题是,如果展示这个webview的宽度不等于设备的宽度的时候,就会出现网页内容过宽左右可以滑动或者网页左右内容没有占满。找了一下,有两个解决方法:

1. 利用webview中的scrollview的zoom特性,这个方法会让网页内容变小

 

- (void)webViewDidFinishLoad:(UIWebView *)theWebView
{
  CGSize contentSize = theWebView.scrollView.contentSize;
  CGSize viewSize = self.view.bounds.size;

  float rw = viewSize.width / contentSize.width;

  theWebView.scrollView.minimumZoomScale = rw;
  theWebView.scrollView.maximumZoomScale = rw;
  theWebView.scrollView.zoomScale = rw;  
}

 

 

2. 第二个方法,在客户端使用js重写meta标签,这个也是在webview的delegate的webViewDidFinished回调中调用;我们使用的这种方法来操作,内容不会变小

 

javascript = [NSString stringWithFormat:@"var viewPortTag=document.createElement('meta');  \
              viewPortTag.id='viewport';  \
              viewPortTag.name = 'viewport';  \
              viewPortTag.content = 'width=%d; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;';  \
              document.getElementsByTagName('head')[0].appendChild(viewPortTag);" , (int)authWebView.bounds.size.width];

[authWebView stringByEvaluatingJavaScriptFromString:javascript];

 

 

参考:

1. http://stackoverflow.com/questions/10666484/html-content-fit-in-uiwebview-without-zooming-out 

2. http://stackoverflow.com/questions/5594447/webpage-in-uiwebview-doesnt-autoresize-correctly-when-uiwebviews-width-is-less

3:http://m.blog.csdn.NET/blog/lihei12345/43565859

用户评论