定义一个获取图片
@property(nonatomic,strong)NSMutableArray *imgUrlArray;
- (NSMutableArray *)imgUrlArray { if (!_imgUrlArray) { _imgUrlArray = [NSMutableArray array]; } return _imgUrlArray; }
初始化webview 没有头部的添加上头部
NSString *htmlString = [NSString stringWithFormat:@"内容",_newtitle,_content];
[_webView loadHTMLString:htmlString baseURL:nil];
附上头部内容格式
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes\" /><style type=\"text/css\">img{width:100%%}</style></head><body><br><center><font style=\"text-align:center;font-size:20px;\">%@</font></center><br><hr width=\"100%%\" color=#dbdbdb SIZE=1 /><div style=\"padding-right: 10px;padding-left: 10px\"><font style=\"line-height:1.5;\" >%@</font></div></body></html>
接着就是写webview的代理了
/**
* 开始加载webView
*/
- (void)webViewDidStartLoad:(UIWebView *)webView {
//@"正在加载"
}
/**
* webView加载完成
*/
- (void)webViewDidFinishLoad:(UIWebView *)webView {
// 网页注入JS获取图片资源、添加点击事件
//这里是js,主要目的实现对url的获取
static NSString * const jsGetImages = @"function getImages(){\
var objs = document.getElementsByTagName(\"img\");\
var imgScr = '';\
for(var i=0;i<objs.length;i++){\
imgScr = imgScr + objs[i].src + '+';\
};\
return imgScr;\
};";
[webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法
NSString *urlResurlt = [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];
[self.imgUrlArray setArray:[urlResurlt componentsSeparatedByString:@"+"]];
if (self.imgUrlArray.count >= 2) {
[self.imgUrlArray removeLastObject];
}
//图片添加点击js
[webView stringByEvaluatingJavaScriptFromString:@"function registerImageClickAction(){\
var imgs=document.getElementsByTagName('img');\
var length=imgs.length;\
for(var i=0;i<length;i++){\
img=imgs[i];\
img.onclick=function(){\
window.location.href='image-preview:'+this.src}\
}\
}"];
[webView stringByEvaluatingJavaScriptFromString:@"registerImageClickAction();"];
}
处理点击事件 执行跳转界面显示图片 或者其他显示图片事件
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
//预览图片
if ([request.URL.scheme isEqualToString:@"image-preview"]) {
//操作
}
return YES;
}
* webView加载失败
*/
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
[SVProgressHUD dismiss];
[MBProgressHUD showInfoMessage:@"加载失败"];
}