iOS-UIWebView加载HTMLString图片显示超过屏
2016-11-06 本文已影响2383人
一位不愿透露姓名的王先生_
简单介绍一下使用
[self.webView loadHTMLString:htmls baseURL:nil]
单纯加载HTMLString
的小技巧。
- 主要解决的是当加载的
HTMLString
既有文字又有图片时,图片没有缩放,导致图片宽度超过屏幕宽度,使得webView
整体左右都可以滑动,这样效果非常不好(见下图):


效果不好的代码如下:
-
注:以下方法是在网络请求成功回调里面调用的
// 网络请求加载的数据,进行字典转模型
NSDictionary *dict = [result objectForKey:@"data"];
HQNewsDetailModel *model = [HQNewsDetailModel mj_objectWithKeyValues:dict];
// model.details就是后台返回的HTMLString
NSString *htmlString = [NSString stringWithString:model.details];
// webView直接加载HTMLString
[self.webView loadHTMLString:htmls baseURL:nil];
经过调整以后(见下图):

调整后的代码如下:
-
注:以下方法是在网络请求成功回调里面调用的
// 网络请求加载的数据,进行字典转模型
NSDictionary *dict = [result objectForKey:@"data"];
HQNewsDetailModel *model = [HQNewsDetailModel mj_objectWithKeyValues:dict];/**
- model.details就是后台返回的HTMLString
- " $img[p].style.width = '100%%';\n"--->就是设置图片的宽度的
- 100%代表正好为屏幕的宽度
*/
NSString *htmlString = [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>",model.details];
// webView直接加载HTMLString
[self.webView loadHTMLString:htmlString baseURL:nil];
