WebVeiw 宽度自适应

  NSString *urlStr = [NSString stringWithFormat:@"<html><head></head><body>%@</body></html>",detailModel.content];
    WebView.scrollView.bounces = NO;
    WebView.scalesPageToFit=NO;
    [WebView loadHTMLString:urlStr baseURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",HOST_URL]]];
    

    
    //html是否加载完成
    isLoadingFinished = NO;

    //第一次加载先隐藏webview
    [WebView setHidden:YES];
    
 
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
     if(navigationType==UIWebViewNavigationTypeLinkClicked)//判断是否是点击链接
     {
         return NO;
     }
     else{return YES;}
 }
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    //若已经加载完成,则显示webView并return
    if(isLoadingFinished)
    {
        [WebView setHidden:NO];
        return;
    }
    
    //js获取body宽度
    NSString *bodyWidth= [webView stringByEvaluatingJavaScriptFromString: @"document.body.scrollWidth "];
    
    int widthOfBody = [bodyWidth intValue];
    
    //获取实际要显示的html
    NSString *html = [self htmlAdjustWithPageWidth:widthOfBody
                                              html:[NSString stringWithFormat:@"<html><head></head><body>%@</body></html>",detailModel.content]
                                           webView:webView];
    
    //设置为已经加载完成
    isLoadingFinished = YES;
    //加载实际要现实的html
    [WebView loadHTMLString:html baseURL:nil];
    
    
/
  }
//获取宽度已经适配于webView的html。这里的原始html也可以通过js从webView里获取
- (NSString *)htmlAdjustWithPageWidth:(CGFloat )pageWidth
                                 html:(NSString *)html
                              webView:(UIWebView *)webView
{
    NSMutableString *str = [NSMutableString stringWithString:html];
    //计算要缩放的比例
    CGFloat initialScale = webView.frame.size.width/pageWidth;
    //将</head>替换为meta+head
    NSString *stringForReplace = [NSString stringWithFormat:@"<meta name=\"viewport\" content=\" initial-scale=%f, minimum-scale=0.1, maximum-scale=2.0, user-scalable=yes\"></head>",initialScale];
    
    NSRange range =  NSMakeRange(0, str.length);
    //替换
    [str replaceOccurrencesOfString:@"</head>" withString:stringForReplace options:NSLiteralSearch range:range];
    return str;

}

感谢作者    http://borissun.iteye.com/blog/2023712
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值