iOS本地的webview中图片添加查看大图功能
2019-01-26 本文已影响12人
我是七月
奋斗的七月
最近遇到一个问题,接口返回一个html,ios可以直接用webview加载,但是要做一个点击图片,查看大图的功能,这个就需要自己在html元素里面加图片的点击事件,从而在原生里面进行监听!
1、添加点击事件
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
//这里是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()"];
NSMutableArray *mUrlArray = [NSMutableArray arrayWithArray:[urlResurlt componentsSeparatedByString:@"+"]];
NSLog(@"mUrlArray==:%@", mUrlArray);
//添加图片可点击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();"];
}
上面的mUrlArray数组里面是所有的图片资源Url地址
1、监听点击事件
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *urlString = [[request URL] absoluteString];
urlString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];
NSLog(@"urlString=%@---urlComps=%@",urlString,urlComps);
if ([request.URL.scheme isEqualToString:@"image-preview"]) {
NSLog(@"查看大图-%@",urlComps);
}
return YES;
}