美文网首页
UIWebView中点击图片查看大图

UIWebView中点击图片查看大图

作者: 可惜你不是我的双子座 | 来源:发表于2018-06-20 11:19 被阅读27次

1.功能概述

1.tableView的HeaderView放一个webView。其中tableView是评论区,webView是一篇文章(后台返回的html)。
2.点击webView中的任意一张图片,展示当前图片的大图以及支持左右滑动查看上一张或下一张图片,并且支持保存图片的功能。

webview中点击查看大图使用了WebViewJavascriptBridge库,不会使用的请查看👉WebViewJavascriptBridge为OC和JS建立桥梁
代码可分为五部分:
1.初始化

// 添加tableview
- (void)addTableView {
    
    switchTableView
    =[[UITableView alloc] initWithFrame:CGRectMake(_tableViewRect.origin.x, _tableViewRect.origin.y + CGRectGetMaxY(self.commentWebView.frame), _tableViewRect.size.width, _tableViewRect.size.height) style:UITableViewStylePlain];
    switchTableView.delegate=self;
    switchTableView.dataSource=self;
    switchTableView.tableFooterView = [[UIView alloc] init];
    
    [switchTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kNewCommentCell];
    [switchTableView registerClass:[NDFPostDetailTableViewCell class] forCellReuseIdentifier:kPostDetailCell];
    [self.view addSubview:switchTableView];
    
    view = [[UIView alloc] initWithFrame:CGRectMake(0,0,kScreenWidth,1)];
    switchTableView.tableHeaderView = view; // 设置tablView的头
    self.commentWebView = [[UIWebView alloc] initWithFrame:CGRectMake(10,0,kScreenWidth-20,1)];
    self.commentWebView.opaque = NO; 
    self.commentWebView.backgroundColor = kMainWhiteColor;
    self.commentWebView.scrollView.scrollEnabled=NO;
    [self.commentWebView sizeToFit];
    
    // 打印日志
    [WebViewJavascriptBridge enableLogging];
    self.bridge = [WebViewJavascriptBridge bridgeForWebView:self.commentWebView];
    [self.bridge setWebViewDelegate:self];
    
    // 点击图片响应事件
    [self.bridge registerHandler:@"imageClick" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        // 利用CollectionView展示所有图片
        [[UIApplication sharedApplication].keyWindow addSubview:self.photoCollectionView];
        [self.photoCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.left.right.bottom.equalTo([UIApplication sharedApplication].keyWindow).offset(0);
        }];
        [self.photoCollectionView bringSubviewToFront:self.view];
        self.imageArray = data[@"allImg"];
        [self.photoCollectionView reloadData];

        // 在设置内容偏移量之前立即强制它进行布局。
        [self.photoCollectionView layoutIfNeeded]; 
        for (NSInteger i = 0; i < [data[@"allImg"] count]; i++) {
            
            if ([data[@"allImg"][i] isEqualToString:data[@"currImg"]]) {
                
                // 判断当前图片并偏移到当前图片位置
                self.photoCollectionView.contentOffset = CGPointMake(kScreenWidth * i, 0);
            }
        }
    }];
}

问题

这里会遇到一个问题,那就是第一次不管你点击哪一张图片,都从第一张开始显示,之后就正常了,也就是说之后你点击第三张,就显示当前第三张图片。

解决方案

I noticed that the sizing information was off after doing reloadData, so I realized I needed to force it to layout immediately before setting the content offset back.
大概意思就是:在做reloadData之后,尺寸信息已经关闭了,所以需要在设置内容偏移量之前立即强制它进行布局。

2.获取html数据

// 请求帖子详情
-(void)requestPosts{

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        int status = [responseObject[@"status"] intValue];
        if (status == 0) {

            self.postModel = [[NDFPostDetailModel alloc] initWithDictionary:responseObject[@"data"][@"posts"] error:nil];
            // 添加样式以及点击webview中图片的点击事件
            NSString *htmlString = [NSString stringWithFormat:@"<html> \n"
                                    "<head> \n"
                                    "<meta charset='utf-8' />"
                                    "<meta name='viewport' content='width=device-width, initial-scale=1'>"
                                    "<style type=\"text/css\"> \n"
                                    "body {font-size:15px;}"
                                    ".posts-content{font-size:15px;}"
                                    ".posts-content img{border: 0;max-width:100%%;}"
                                    ".posts-content p{margin-bottom:.8em;}"
                                    ".posts-content p img{display:block;margin: 0 auto;}\n"
                                    "</style> \n"
                                    "</head> \n"
                                    "<body>"
                                    "<div class='posts-content'>"
                                    "%@"
                                    "</div>"
                                    "<script >var setupWebViewJavascriptBridge=function(e){if(window.WebViewJavascriptBridge)return e(WebViewJavascriptBridge);if(window.WVJBCallbacks)return window.WVJBCallbacks.push(e);window.WVJBCallbacks=[e];var t=document.createElement('iframe');t.style.display='none',t.src='https://__bridge_loaded__',document.documentElement.appendChild(t),setTimeout(function(){document.documentElement.removeChild(t)},0)};setupWebViewJavascriptBridge(function(e){for(var t=document.getElementsByClassName('posts-content')[0],n=t.getElementsByTagName('img'),i=[],a=0;a<n.length;a++)i.push(n[a].src),n[a].onclick=function(t){t.preventDefault(),e.callHandler('imageClick',{currImg:this.src,allImg:i},function(e){})}});</script>"
                                    "</body>"
                                    "</html>",self.postModel.posts_content];
            
            // 加载html
            [self.commentWebView loadHTMLString:htmlString baseURL:nil];
            // 头部添加webview
            [view addSubview:self.commentWebView];
            // 通知webview中内容高度的变化
            [self.commentWebView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
            
            [switchTableView reloadData];
        }
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        if (error.code  == -1009) {
            [SVProgressHUD showErrorWithStatus:@"请检查网络"];
        } else {
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        }
        
    }];
}

这里需要注意两三个问题:

1.我们需要对返回回来的html做一些样式的处理,比如文字的大小以及图片的自适应,这样就不会有图片超出屏幕外的情况。
2.在样式处理的代码中添加图片的点击事件。
3.webview的高度变化利用通知中心来处理。

3.获取webview的正确高度

#pragma mark -- UIWebViewDelegate
- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context {
    
    if([keyPath isEqualToString:@"contentSize"]) {
        
        webViewHeight= [[self.commentWebView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"]floatValue];
    
        // 头部
        [view addSubview:self.headerBgView];
        
        if (self.postModel.posts_title.length == 0) {
            
            artTitleLabelHeight = 0;
        }else {
            
            // 标题
            [self.headerBgView addSubview:self.artTitleLabel];
            // 自适应高度
            artTitleLabelHeight = [ZYUIFactory labelAdaptiveHeightWithTextAlignment:NSTextAlignmentLeft withString:self.postModel.posts_title withFont:[UIFont systemFontOfSize:20] withLabel:self.artTitleLabel withSize:CGSizeMake(kScreenWidth-15-15, CGFLOAT_MAX)];
        }
        
        // 头像
        [self.headerBgView addSubview:self.iconBtn];
        
        if (![[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"]] isEqualToString:self.postModel.user_id]) {
            
            // 关注按钮
            [self.headerBgView addSubview:self.concerBtn];
        }
        
        // 名称
        [self.headerBgView addSubview:self.nameLabel];
        
        if ([self.postModel.user_sign integerValue] != 0) {
            
            [self.headerBgView addSubview:self.userSignLabel];
        }
        
        [self.headerBgView addSubview:self.levelNameLabel];
        
        // 时间
        [self.headerBgView addSubview:self.titleLabel];
        
        if ([self.postModel.posts_points integerValue] != 0) {
            
            [self.headerBgView addSubview:self.rewardsOrPunishImage];
            [self.headerBgView addSubview:self.numLabel];
        }
        
        // 分割线
        [self.headerBgView addSubview:self.topLineImage];
        
        CGRect newFrame = self.commentWebView.frame;
        newFrame.size.height = webViewHeight;
        self.commentWebView.frame = newFrame;
        CGRect Frame = view.frame;
        Frame.size.height= Frame.size.height+self.commentWebView.frame.size.height;
        
        // 底部
        [view addSubview:self.footerBgView];
        [self.footerBgView addSubview:self.lookLabel];
        [self.footerBgView addSubview:self.bottomLineImage];
        
        CGFloat topFloat = 0;
        if (self.postModel.posts_title.length == 0) {
            
            if ([self.postModel.posts_points integerValue] != 0) {
                
                topFloat = artTitleLabelHeight +15+40 +1 + 45;
            }else {
                
                topFloat = artTitleLabelHeight +15+40 +20+1;
            }
        }else {
            
            if ([self.postModel.posts_points integerValue] != 0) {
                
                topFloat = 15+artTitleLabelHeight +15+40 +1 + 45;
            }else {
                
                topFloat = 15+artTitleLabelHeight +15+40 +20+1;
            }
        }
        
        CGFloat footFloat = 60;
        view.frame = CGRectMake(newFrame.origin.x, newFrame.origin.y, newFrame.size.width, newFrame.size.height+ topFloat + footFloat);
        
        [switchTableView setTableHeaderView:view];//这句话才是重点
    }
}

- (void)webViewDidFinishLoad:(UIWebView*)webView {
    
    CGFloat sizeHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
    
    if (self.postModel.posts_title.length == 0) {
        
        if ([self.postModel.posts_points integerValue] != 0) {
            
            self.commentWebView.frame = CGRectMake(10,artTitleLabelHeight +15+40 +1 + 45,kScreenWidth-20, sizeHeight);
        }else {
            
            self.commentWebView.frame = CGRectMake(10,artTitleLabelHeight +15+40 +20+1,kScreenWidth-20, sizeHeight);
        }
    }else {
        
        if ([self.postModel.posts_points integerValue] != 0) {
            
            self.commentWebView.frame = CGRectMake(10,15+artTitleLabelHeight +15+40 +1 + 45,kScreenWidth-20, sizeHeight);
        }else {
            
            self.commentWebView.frame = CGRectMake(10,15+artTitleLabelHeight +15+40 +20+1,kScreenWidth-20, sizeHeight);
        }
    }
    
}

4.销毁通知中心

- (void)dealloc {
    
    [self.commentWebView.scrollView removeObserver:self forKeyPath:@"contentSize" context:nil ];
}

5.展示图片以及图片保存功能

#pragma mark -- UICollectionViewDelegate && UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.imageArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NDFPhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:KPhotoCell forIndexPath:indexPath];
    
    [cell refreshUIWithArray:self.imageArray indexPath:indexPath];
    // 点击图片就移除collectionview
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
    [cell.photo addGestureRecognizer:tap];
    
    __weak __typeof(cell) weakCell = cell;
    // 图片上有一个保存按钮
    cell.saveBtnClickBlock = ^(UIButton *saveBtn, NSIndexPath *indexPath) {
        
        UIImageWriteToSavedPhotosAlbum(weakCell.photo.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    };
    
    // 增加长按事件,
    UILongPressGestureRecognizer *longPressPR = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longImagePressAction:)];
    longPressPR.minimumPressDuration = 1;
    [cell.photo addGestureRecognizer:longPressPR];
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake(kScreenWidth, kScreenHeight);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    
    return 0.0f;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    
    return 0.0f;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

// 移除photoCollectionView
- (void)tapClick {
    
    [self.photoCollectionView removeFromSuperview];
}

// 长按手势方法
- (void)longImagePressAction:(UILongPressGestureRecognizer *)sender {
    
    if (sender.state == UIGestureRecognizerStateBegan) {
        
        self.currentImage = (UIImageView *)sender.view;
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"保存图片", nil];
        
        [sheet showInView:self.view];
    }
}

#pragma mark -- UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 0) {
        
        UIImageWriteToSavedPhotosAlbum(self.currentImage.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    if (error) {
        
        [SVProgressHUD showImage:nil status:@"  图片保存相册失败  "];
    }else {
        
        [SVProgressHUD showImage:nil status:@"  图片已保存到相册  "];
    }
}

效果展示.png

参考:
UITableView和UICollectionView-reloadData后setContentOffset无效解决
TableView上的HeaderView放WebView

相关文章

网友评论

      本文标题:UIWebView中点击图片查看大图

      本文链接:https://www.haomeiwen.com/subject/ooolzxtx.html