在 javascript 中修改图像大小后 WKWebView 未更改 contentSize

WKWebView not changing contentSize after modify images sizes in javascript

我将 WKWebView 与 loadHTMLString 和 basicURL 一起使用。 我观察 "scrollView.contentSize" 路径的变化并在内容大小变化时执行下一个代码:

if (textWebViewHeightConstraint.constant != textWebView.scrollView.contentSize.height) {
   CGFloat newSize = textWebView.scrollView.contentSize.height;
   if (!self.currentPromo.text || self.currentPromo.text.length == 0) {
       newSize = 0.0;
   }
   [UIView animateWithDuration:kDefaultAnimationDuration animations:^{
       textWebViewHeightConstraint.constant = newSize;
       [self.view layoutIfNeeded];
   }];
}

它工作正常。 但是我的 html 字符串有时包含具有静态宽度和高度的大图像。

我在 didFinishNavigation 方法中修改图片大小:

[webView evaluateJavaScript:@"var images = document.getElementsByTagName('img');"
 "for(var i = 0; i < images.length; i++) {"
    "images[i].style.height = \"auto\";"
    "images[i].style.maxWidth = window.innerWidth - kDefaultMargin * 2;"
 "}" completionHandler:nil];

执行这段JS代码后,content height改变了,但是WKWebView没有检测到,也没有改变content size。结果我在内容结束后在 WKWebView 中有一个很大的免费 space。

我该如何解决?

谢谢。

我修好了! 我不知道,为什么 WKWebView 内容大小不会自动调整大小,但我们可以帮他做。

如果你遇到和我一样的问题,你应该:

Delcare BOOL 属性

@property(nonatomic, assign) BOOL isWebViewReloaded;

并在更新视图内容方法中设置为 NO 值

self.isWebViewReloaded = NO;
NSString *wrappedText = [self.currentPromo wrappedTextForWebViewForWith:self.textWebView.bounds.size.width andText:nil];
[self.textWebView loadHTMLString:wrappedText baseURL:[ApiClient shared].baseUrl];

我的包装方法将 html 和正文标签添加到 html 字符串

-(NSString *)wrappedTextForWebViewForWith:(CGFloat)width andText:(NSString *)text {
    if (!text) {
        text = self.text;
    }
    return [NSString stringWithFormat:
            @"<html>"
                "<head>"
                    "<meta name=\"viewport\" content=\"initial-scale=1.0\" />"
                "</head>"
                "<body style=\"max-width:%fpx\">"
                    "%@"
                "</body>"
            "</html>", width, text];
}

在 didStartProvisionalNavigation 委托方法中,您应该手动将内容大小设置为零。 很重要,没有它的WKWebView是不会resize的!

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
    webView.scrollView.contentSize = CGSizeZero;
}

在 didFinishNavigation 委托方法中,您应该修改已经加载的文档并使用修改后的 html

重新加载 WKWebView
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    [webView evaluateJavaScript:self.modifyImagesJS completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
         if (!self.isWebViewReloaded) {
             //it is very big hack! See my question for details: 
             [webView evaluateJavaScript:@"document.body.innerHTML" completionHandler:^(id _Nullable str, NSError * _Nullable error) {
                 self.isWebViewReloaded = YES;
                 NSString *wrappedHTML = [self.currentPromo wrappedTextForWebViewForWith:self.textWebView.bounds.size.width andText:str];
                 [self.textWebView loadHTMLString:wrappedHTML baseURL:[ApiClient shared].baseUrl];
             }];
         }
     }];
}

我的 isWebViewReloaded 脚本:

self.modifyImagesJS = [NSString stringWithFormat:@""
                       "var images = document.getElementsByTagName('img');"
                       "for(var i = 0; i < images.length; i++) {"
                            "images[i].removeAttribute(\"height\");"
                            "images[i].style.height = \"auto\";"
                            "images[i].style.maxWidth = window.innerWidth - %f * 2;" //  %f * 2 - сompensate left and right margins
                       "}", kDefaultSmallBlocksMargins];

最后我使用 KVO 检测 webview 内容大小变化并修改 webview 高度限制

FBKVOController *kvo = self.KVOController;
[kvo observe:self.textWebView
     keyPath:@"scrollView.contentSize"
     options:NSKeyValueObservingOptionNew
       block:^(id _Nullable observer, WKWebView * _Nonnull webView, NSDictionary<NSString *,id> * _Nonnull change) {
           if (webView.constraints.firstObject.constant != webView.scrollView.contentSize.height) {
               NSLog(@"new size is %f", webView.scrollView.contentSize.height);
               CGFloat newSize = webView.scrollView.contentSize.height;
               if (!_self.currentPromo.text || _self.currentPromo.text.length == 0) {
                   newSize = 0.0;
               }
               [UIView animateWithDuration:kDefaultAnimationDuration animations:^{
                   webView.constraints.firstObject.constant = newSize;
                   [_self.view layoutIfNeeded];
               }];
           }
       }];

宾果!!!

原始html字符串:

... <img width="600" src="/upload/someName.png" height="2001">...

Html 修改后的字符串

...  <img width="600" src="/upload/someName.png" style="height: auto; max-width: 284px;"> ...

内容大小的变化

...[26964:10644727] new size is 2297.000000
...[26964:10644727] new size is 0.000000
...[26964:10644727] new size is 1243.000000