后台返回 一段html字符串 里面有图片但是图片很大 webview 的content会出现上下和左右滑动的滚动条,为了让图片适应webview 宽度做了一些修改。
1.首先得有一个webview
UIWebView * detailWebView = [[UIWebView alloc] initWithFrame:yourFrame];
detailWebView.delegate = self;
NSString * webContentStr = [self.infoDict stringForKey:@"Description"];
NSLog(@"webContentStr==%@",webContentStr);
[detailWebView loadHTMLString:webContentStr baseURL:nil];
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//图片适应宽高
[webView stringByEvaluatingJavaScriptFromString:
@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function ResizeImages() { "
"var myimg,oldwidth;"
"var maxwidth=document.body.clientWidth;" //缩放系数</span>
"for(i=0;i <document.images.length;i++){"
"myimg = document.images[i];"
"if(myimg.width > maxwidth){"
"oldwidth = myimg.width;"
"myimg.width = maxwidth;"
"myimg.height = myimg.height * (maxwidth/oldwidth);"
"}"
"}"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);"];
[webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
//webview 的高度适应内容高度(若不想适应可以去掉下面这些)
NSString *curHeight = [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"];//缩放后的内容高度
// UIScrollView *scrollView = (UIScrollView *)[[webView subviews] objectAtIndex:0];//这两行是么可有缩放的情况下内容高度
// CGFloat webViewHeight = [scrollView contentSize].height;
CGRect newFrame = webView.frame;
newFrame.size.height = [curHeight floatValue];
webView.frame = newFrame;
}