IOS 设置UIViewController为背景半透明浮层弹窗,查看富文本图片详情

使用场景:UIViewController1 打开 UIViewController2(背景半透明弹窗)

案例:打开富文本网页图片的url查看图片详情

WKWebView  WKNavigationDelegate代理方法设置js代码点击事件 

///注册添加图片标签点击js方法
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    ///js添加图片点击事件
    NSString *jsClickImage =@"function registerImageClickAction(){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.onclick=function(){window.location.href='image-preview:'+this.src}}}";
    
    [webView evaluateJavaScript:jsClickImage completionHandler:nil];
    [webView evaluateJavaScript:@"registerImageClickAction()" completionHandler:nil];
    
    [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result,NSError *_Nullable error) {
        //获取webView内容高度
        CGFloat height = [result doubleValue];
//        [webView mas_updateConstraints:^(MASConstraintMaker *make) {
//              make.height.equalTo(@(height));
//        }];
        webView.frame = CGRectMake(0, 0, self.frame.size.width, height);
        [webView layoutIfNeeded];
        [webView setNeedsLayout];
        if (self.contentHeightCallback != nil) {
            self.contentHeightCallback(CGSizeMake(self.frame.size.width, height));
        }
    }];
    
}

///拦截点击图片
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSString *requestString = navigationAction.request.URL.absoluteString;
    NSString *imgKey = @"image-preview";
    if([requestString hasPrefix: imgKey]){
        NSString *url = [requestString substringFromIndex:imgKey.length+1];
        //查看图片详情
        [self showPicDetail:url];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

showPicDetail:()  方法打开浮窗:

-(void) showPicDetail:(NSString *)imgUrl{
    ShowBigPicDetailViewController *vc = [[ShowBigPicDetailViewController alloc] init];
    vc.imageUrl = imageUrl;
    //设置全屏显示   关键语句,必须有
    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    [self presentViewController:vc animated:YES completion:nil];
}

设置UIViewController2 背景半透明

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置半透明背景
    [self.view setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5f]];
    ...
}

关闭浮窗弹窗:

[self dismissViewControllerAnimated:YES completion:nil];

你可能感兴趣的:(ios,html,WKWebView,OC,富文本图片)