iOS WKWebView 加载富文本图片适配

NSString *htmls = [NSString stringWithFormat:@" \n"
                           " \n"
                           " \n"
                           " \n"
                           ""
                           "%@"
                           ""
                           "",htmlString];

[self.webView loadHTMLString:htmls baseURL:nil];

下面是适配内容方法

 NSString *injectionJSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content','width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";

    WKUserScript *injectionJSStringScript = [[WKUserScript alloc] initWithSource:injectionJSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];

    NSMutableString *javascript = [NSMutableString string];
    [javascript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];//禁止长按
    [javascript appendString:@"document.documentElement.style.webkitUserSelect='none';"];//禁止选择
    WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        
    WKUserContentController *userController = [WKUserContentController new];
    [userController addUserScript:injectionJSStringScript];
    [userController addUserScript:noneSelectScript];
        
    WKWebViewConfiguration *config          = [[WKWebViewConfiguration alloc]init];
    config.preferences                      = [WKPreferences new];
    config.preferences.minimumFontSize      = 10;
    config.preferences.javaScriptEnabled    = YES;
    config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
    
    config.userContentController = userController;
    
    self.wkWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0,AP_ScreenWidth, 3000) configuration:config];
     self.wkWebView.scrollView.scrollEnabled    = NO;
     self.wkWebView.scrollView.bounces          = NO;
     self.wkWebView.userInteractionEnabled      = NO;
    if (@available(iOS 11.0, *)) {
        self.wkWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
     self.wkWebView.navigationDelegate = self;
     self.wkWebView.scrollView.delegate = self;
     //监听wekwebview 的高度来获取webview高度
   //  [self.wkWebView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
    
    [self addSubview:self.wkWebView];

github推荐
感谢作者@蚯小麦

你可能感兴趣的:(iOS WKWebView 加载富文本图片适配)