美文网首页
iOS WebView 图片点击放大并左右滑动,类似微信/网易

iOS WebView 图片点击放大并左右滑动,类似微信/网易

作者: 刘祺旭 | 来源:发表于2017-09-14 17:48 被阅读363次

这是我来简书写的第一篇文章,原本我是CSDN的一个小码农,因为好友的极力推荐,我来到了简书,希望和大家一起共同学习成长
原博客地址:http://blog.csdn.net/q644419002

前言:事情起因是有小伙伴问我能不能实现原生加载任意网页(不需要H5工程师支持)都可以实现类似微信公众号那种图片点击放大,还能左右滑动的功能?我说:这东西网上肯定有实现吧,你百度看看就好了.结果他一会回来说,网上的都太老了,逻辑也不清楚,只有简单的当前图片放大,而且想用新的WKWebView来实现,毕竟UIWebView太老旧了.于是我寻思,要不来简书写一篇博客吧.

来写博之前,先弄了个demo(表示对大家的崇高敬意,和怀着严谨的风格),当然了,本人代码不精,封装无力,架构松散,如有更好方法,欢迎大神不吝赐教~本篇如果能对正好需要的朋友有所帮助,我就心满意足了

话不多说,直接上代码吧

- (void)viewDidLoad {
    [super viewDidLoad];
    WKWebViewConfiguration *confifg = [[WKWebViewConfiguration alloc] init];
    confifg.selectionGranularity = WKSelectionGranularityCharacter;
    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(14, 64, CurrentScreenWidth - 28, CurrentScreenHeight - 64) configuration:confifg];
    _webView.opaque = NO;
    _webView.navigationDelegate = self;
    _webView.UIDelegate = self;
    _webView.scrollView.bounces=NO;
    _webView.backgroundColor=[UIColor whiteColor];
    _webView.scrollView.decelerationRate=UIScrollViewDecelerationRateNormal;
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E5%87%A4%E5%87%B0%E7%BD%91"]];//百度随便找个地址 主要验证demo使用
    [_webView loadRequest:request];
    _webView.scrollView.delegate = self;
    [self.view addSubview:_webView];
}

这块就是WKWebView的创建和使用
下面是重头戏

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{ //加载页面完成

    //js方法遍历图片添加点击事件 返回图片个数
    /*这块我着重说几句
     逻辑:
     1.遍历获取全部的图片;
     2.生成一个Srting为所有图片的拼接,拼接时拿到所处数组下标;
     3.为图片添加点击事件,并添加数组所处下标
     注意点:
     1.如果仅仅拿到url而无下标的话,网页中如果有多张相同地址的图片 则会发生位置错乱
     2.声明时不要用 var yong let  不然方法添加的i 永远是length的值
     */
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var objs = document.getElementsByTagName(\"img\");\
    var imgScr = '';\
    for(let i=0;i<objs.length;i++){\
    imgScr = imgScr + objs[i].src +'LQXindex'+ i +'L+Q+X';\
    objs[i].onclick=function(){\
    document.location=\"myweb:imageClick:\"+this.src + 'LQXindex' + i;\
    };\
    };\
    return imgScr;\
    };";
    [webView evaluateJavaScript:jsGetImages completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        
    }];
    //注入自定义的js方法后别忘了调用 否则不会生效(不调用也一样生效了,,,不明白)
    
    [webView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSString *urlResurlt = result;
        allUrlArray = [NSMutableArray arrayWithArray:[urlResurlt componentsSeparatedByString:@"L+Q+X"]];
        if (allUrlArray.count >= 2) {
            [allUrlArray removeLastObject];// 此时数组为每一个图片的url
        }
    }];
    
}

对的,在加载页面完成后 ,完全用JS做的处理,我有一个朋友和我说这种做法路子太野,并不太健壮,我也有这个感觉,打算这篇文章写完后,再看看有没有更好的方式,如果有,我会以iOS WebView 图片点击放大并左右滑动,类似微信/网易文章功能(二)的形式再发一篇的.先分析一波代码吧
逻辑:
1.遍历获取全部的图片;
2.生成一个Srting为所有图片的拼接,拼接时拿到所处数组下标;
3.为图片添加点击事件,并添加数组所处下标
注意点:
1.如果仅仅拿到url而无下标的话,网页中如果有多张相同地址的图片 则会发生位置错乱
2.声明时不要用 var 要用 let 不然方法添加的i 永远是length的值(感谢朋友:赵奇H5工程师的指正,让我少走了不少弯路)
3.拼接字符串的标示字符串尽可能的用的复杂一点,这里越复杂,代码出错误的几率也就越低

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSString *requestString = [[navigationAction.request URL] absoluteString];
    //hasPrefix 判断创建的字符串内容是否以pic:字符开始
    if ([requestString hasPrefix:@"myweb:imageClick:"]) {
        NSString *imageUrl = [requestString substringFromIndex:@"myweb:imageClick:".length];
        if (bgView) {
            //设置不隐藏,还原放大缩小,显示图片
            bgView.hidden = NO;
            NSArray *imageIndex = [NSMutableArray arrayWithArray:[imageUrl componentsSeparatedByString:@"LQXindex"]];
            int i = [imageIndex.lastObject intValue];
            [bgView setContentOffset:CGPointMake(CurrentScreenWidth *i, 0)];
        }else{
            [self showBigImage:imageUrl];//创建视图并显示图片
        }
        
    }
    
    
    decisionHandler(WKNavigationActionPolicyAllow);
    
}
#pragma mark 显示大图片
-(void)showBigImage:(NSString *)imageUrl{
    //创建灰色透明背景,使其背后内容不可操作
    bgView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, CurrentScreenWidth, CurrentScreenHeight)];
    [bgView setBackgroundColor:[UIColor colorWithRed:0.3 green:0.3 blue:0.3 alpha:0.7]];
    bgView.contentSize = CGSizeMake(CurrentScreenWidth *allUrlArray.count, CurrentScreenHeight);
    bgView.pagingEnabled = YES;
    [self.view addSubview:bgView];
    
    //创建关闭按钮
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    closeBtn.backgroundColor = [UIColor redColor];
    [closeBtn addTarget:self action:@selector(removeBigImage) forControlEvents:UIControlEventTouchUpInside];
    [closeBtn setFrame:CGRectMake(CurrentScreenWidth/2.0 - 13, 200, 26, 26)];
    [self.view addSubview:closeBtn];
    
    //创建显示图像视图
    for (int i = 0; i < allUrlArray.count; i++) {
        UIView *borderView = [[UIView alloc] initWithFrame:CGRectMake(CurrentScreenWidth *i, (CurrentScreenHeight - 240)/2.0, CurrentScreenWidth-20, 240)];
        [bgView addSubview:borderView];
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, CGRectGetWidth(borderView.frame)-20, CGRectGetHeight(borderView.frame)-20)];
        imgView.userInteractionEnabled = YES;
        
        NSArray *imageIndex = [NSMutableArray arrayWithArray:[allUrlArray[i] componentsSeparatedByString:@"LQXindex"]];
        
        [imgView sd_setImageWithURL:[NSURL URLWithString:imageIndex.firstObject] placeholderImage:nil];

        [borderView addSubview:imgView];
        
    }
    NSArray *imageIndex = [NSMutableArray arrayWithArray:[imageUrl componentsSeparatedByString:@"LQXindex"]];
    
    
    int i = [imageIndex.lastObject intValue];
    [bgView setContentOffset:CGPointMake(CurrentScreenWidth *i, 0)];
    
}


//关闭按钮
-(void)removeBigImage
{
    bgView.hidden = YES;
}

再加上这里的实现就可以了,这样就是简单的实现了图片点击放大,并且左右滑动,至于保存图片和缩小放大或者UI界面就非常简单了,我就不在这里献丑了.

*我也是最近才开始使用WKWebView,如果大家有相关问题可以留言,我和大家一起探讨共同进步.

过几天我准备再发一篇,做WKWebView与原生无缝连接实现文章+原生列表的功能,主要难点在网页内容高度获取和图片文字适配的方面.因为WKWebView是取消了scalesPageToFit这个属性的.

那么大家,下次见咯~*

相关文章

网友评论

      本文标题: iOS WebView 图片点击放大并左右滑动,类似微信/网易

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