近期在做一款电商类的App,做到商品详情页时,纠结到了图文详情的适配问题,脑细胞纠结一下午之后,共找到两种方法,一种是在服务端返回的HTML字符串前边拼接上图片的样式,代码如下:
webview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 50, self.frame.size.width, self.frame.size.height-50)];
[self addSubview:webview];
webview.delegate = self;
webview.scalesPageToFit = YES;
webview.dataDetectorTypes = UIDataDetectorTypeAll;
NSString * htmlStyle = @" <style type=\"text/css\"> img{ width: 100%; height: auto; display: block; } </style> ";
webStr = [htmlStyle stringByAppendingString:webStr];
[webview loadHTMLString:webStr baseURL:nil];
webStr是你自己需要加载的图文详情的HTML字符串.
另一种使用到了js交互,代码如下:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
CGFloat width = [[UIScreen mainScreen]bounds].size.width;
NSString *jsStr = [NSString stringWithFormat:@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function ResizeImages() { "
"var myimg,oldwidth;"
"var maxwidth = '%f';" //自定义宽度
"for(i=0;i <document.images.length;i++){"
"myimg = document.images[i];"
"if(myimg.width > maxwidth){"
"oldwidth = myimg.width;"
"myimg.width = maxwidth;"
"}"
"}"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);",width];
[webView stringByEvaluatingJavaScriptFromString:jsStr];
[webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
}
需要注意的是两种方法不可共用,笔者推荐第一种方法,简单粗暴有力,使用第二种方法时webView的设置webview.scalesPageToFit = YES;需要去掉!
效果图如下:
微博关注 清风徐来花满楼 共同讨论学习进步!