转义:
把服务器返回的带>的字符串转化为正常的标签符号
//将 < 等类似的字符转化为HTML中的“<”等
+ (NSString *)htmlEntityDecode:(NSString *)string {
string = [string stringByReplacingOccurrencesOfString:@""" withString:@"\""];
string = [string stringByReplacingOccurrencesOfString:@"'" withString:@"'"];
string = [string stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
string = [string stringByReplacingOccurrencesOfString:@">" withString:@">"];
string = [string stringByReplacingOccurrencesOfString:@"&" 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"];
}
网友评论