How to determine the content size of a UIWebView?

后端 未结 15 2120
灰色年华
灰色年华 2020-11-22 17:06

I have a UIWebView with different (single page) content. I\'d like to find out the CGSize of the content to resize my parent views appropriately. T

15条回答
  •  一整个雨季
    2020-11-22 17:46

    If your HTML contains heavy HTML-contents like iframe's (i.e. facebook-, twitter, instagram-embeds) the real solution is much more difficult, first wrap your HTML:

    [htmlContent appendFormat:@"", [[LocalizationStore instance] currentTextDir], [[LocalizationStore instance] currentLang]];
    [htmlContent appendFormat:@""];
    [htmlContent appendString:@""];
    [htmlContent appendFormat:@"..."]; // Rest of your HTML -section
    [htmlContent appendFormat:@""];
    [htmlContent appendFormat:@""];
    [htmlContent appendFormat:@"
    "]; // !important https://stackoverflow.com/a/8031442/1046909 [htmlContent appendFormat:@"..."]; // Your HTML-content [htmlContent appendFormat:@"
    "]; //
    [htmlContent appendFormat:@""]; [htmlContent appendFormat:@""];

    Then add handling x-update-webview-height-scheme into your shouldStartLoadWithRequest:

        if (navigationType == UIWebViewNavigationTypeLinkClicked || navigationType == UIWebViewNavigationTypeOther) {
        // Handling Custom URL Scheme
        if([[[request URL] scheme] isEqualToString:@"x-update-webview-height"]) {
            NSInteger currentWebViewHeight = [[[request URL] host] intValue];
            if (_lastWebViewHeight != currentWebViewHeight) {
                _lastWebViewHeight = currentWebViewHeight; // class property
                _realWebViewHeight = currentWebViewHeight; // class property
                [self layoutSubviews];
            }
            return NO;
        }
        ...
    

    And finally add the following code inside your layoutSubviews:

        ...
        NSInteger webViewHeight = 0;
    
        if (_realWebViewHeight > 0) {
            webViewHeight = _realWebViewHeight;
            _realWebViewHeight = 0;
        } else {
            webViewHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"content\").offsetHeight;"] integerValue];
        }
    
        upateWebViewHeightTheWayYorLike(webViewHeight);// Now your have real WebViewHeight so you can update your webview height you like.
        ...
    

    P.S. You can implement time delaying (SetTimeout and setInterval) inside your ObjectiveC/Swift-code - it's up to you.

    P.S.S. Important info about UIWebView and Facebook Embeds: Embedded Facebook post does not shows properly in UIWebView

提交回复
热议问题