美文网首页
UIWebView加载HTMLString转义及宽度适配

UIWebView加载HTMLString转义及宽度适配

作者: 倪大头 | 来源:发表于2020-01-08 10:19 被阅读0次

    转义:
    把服务器返回的带&gt的字符串转化为正常的标签符号

    //将 &lt 等类似的字符转化为HTML中的“<”等
    + (NSString *)htmlEntityDecode:(NSString *)string {
        string = [string stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
        string = [string stringByReplacingOccurrencesOfString:@"&apos;" withString:@"'"];
        string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
        string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
        string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"];
        
        return string;
    }
    

    图片宽度适配:

    NSString *htmls = [NSString stringWithFormat:@"<html> \n"
    "<head> \n"
    "<style type=\"text/css\"> \n"
    "body {font-size:15px;}\n"
    "</style> \n"
    "</head> \n"
    "<body>"
    "<script type='text/javascript'>"
    "window.onload = function(){\n"
    "var $img = document.getElementsByTagName('img');\n"
    "for(var p in $img){\n"
        "$img[p].style.width = '100%%';\n"
        "$img[p].style.height ='auto'\n"
    "}\n"
    "}"
    "</script>%@"
    "</body>"
    "</html>", htmlStr];
    

    完整代码:

    NSString *htmlStr = self.dataDic[@"spu_desc"];
    NSString *htmls = [NSString stringWithFormat:@"<html> \n"
    "<head> \n"
    "<style type=\"text/css\"> \n"
    "body {font-size:15px;}\n"
    "</style> \n"
    "</head> \n"
    "<body>"
    "<script type='text/javascript'>"
    "window.onload = function(){\n"
    "var $img = document.getElementsByTagName('img');\n"
    "for(var p in $img){\n"
        "$img[p].style.width = '100%%';\n"
        "$img[p].style.height ='auto'\n"
    "}\n"
    "}"
    "</script>%@"
    "</body>"
    "</html>", [Utils htmlEntityDecode:htmlStr]];
    UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(kScaleX * 15, CGRectGetMaxY(descriptionTitle.frame) + 20, _descriptionView.frame.size.width - kScaleX * 30, 10)];
    webView.delegate = self;
    webView.userInteractionEnabled = NO;
    [webView loadHTMLString:htmls baseURL:nil];
    [_descriptionView addSubview:webView];
    

    webview代理方法中可以获得内容高度:

    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        NSString *contentH = [webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"];
    }
    

    相关文章

      网友评论

          本文标题:UIWebView加载HTMLString转义及宽度适配

          本文链接:https://www.haomeiwen.com/subject/dlbjactx.html