一 实现效果:
在一个TableVeiw中的一个cell上嵌套一个WebView,并且支持网页上的图片浏览;
二 难点分析:
WebView高度不确定,查找HTML中图片,
插入js代码,对图片进行点击操作;
三 设计思想:
1:Load Data And Later:
- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL;
2:
UIWebView Delegate Methods
-(void)webViewDidFinishLoad:(UIWebView *)webView
获取高度:CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
刷新界面:[self.tableView reloadData];
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
[cell.contentView addSubview:_webView];
//插入js代码,对图片进行点击操作
NSString * result = [self.webView stringByEvaluatingJavaScriptFromString:@"function assignImageClickAction(){var imgs=document.getElementsByTagName('img');var length=imgs.length;for(var i=0; i < length;i++){img=imgs[i];if(\"ad\" ==img.getAttribute(\"flag\")){var parent = this.parentNode;if(parent.nodeName.toLowerCase() != \"a\")return;}img.οnclick=function(){window.location.href='image-preview:'+this.src}}}"]; DSLog(@"插入js代码,对图片进行点击操作 %@",result);
NSString * resultAction = [self.webView stringByEvaluatingJavaScriptFromString:@"assignImageClickAction();"];
DSLog(@"resultAction:%@",resultAction);
3:Get Images and nodeCountOfTag
- (NSArray *)getImgs
{
NSMutableArray *arrImgURL = [[NSMutableArray alloc] init];
for (int i = 0; i < [self nodeCountOfTag:@"img"]; i++) {
NSString *jsString = [NSString stringWithFormat:@"document.getElementsByTagName('img')[%d].src", i];
NSString * str = [self.webView stringByEvaluatingJavaScriptFromString:jsString];
[arrImgURL addObject:str];
}
_imageArray = [NSMutableArray arrayWithArray:arrImgURL];
return arrImgURL;
}
//获取某个标签的结点个数
- (NSInteger)nodeCountOfTag:(NSString *)tag
{
NSString *jsString = [NSString stringWithFormat:@"document.getElementsByTagName('%@').length", tag];
int count = [[_webView stringByEvaluatingJavaScriptFromString:jsString] intValue];
return count;
}
4:WebViewImageClickAction
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
if ([request.URL isEqual:@"about:blank"])
{
return true;
}
if ([request.URL.scheme isEqualToString: @"image-preview"])
{
NSString *url = [request.URL.absoluteString substringFromIndex:14];
//启动图片浏览器, 跳转到图片浏览页面
if (_imageArray.count != 0) {
self.imgType = LessonDetailImgTypeLessonContent;
HZPhotoBrowser *browserVc = [[HZPhotoBrowser alloc] init];
browserVc.imageCount = self.imageArray.count; // 图片总数
browserVc.currentImageIndex = [_imageArray indexOfObject:url];//当前点击的图片
browserVc.delegate = self;
[browserVc show];
}
return NO;
}
// 用户点击文章详情中的链接
if ( navigationType == UIWebViewNavigationTypeLinkClicked ) {
DSLog(@"打开链接");
return NO;
}
return YES;
}