Four methods of iOS Webview adaptive height of actual content in detail

  • 2020-12-09 01:03:34
  • OfStack

// The first method


- (void)webViewDidFinishLoad:(UIWebView *)webView
{
CGFloat webViewHeight=[webView.scrollView contentSize].height;
CGRect newFrame = webView.frame;
newFrame.size.height = webViewHeight;
webView.frame = newFrame;
_webTablewView.contentSize = CGSizeMake(320, newFrame.size.height + 64 + KWIDTH - 100);
}

//2. Execute the js statement to directly obtain the dom height of the html document


- (void)webViewDidFinishLoad:(UIWebView *)webView{
CGFloatwebViewHeight =[[webViewstringByEvaluatingJavaScriptFromString:@document.body.offsetHeight]floatValue];
// CGFloat webViewHeight= [[webViewstringByEvaluatingJavaScriptFromString:@document.body.scrollHeight]floatValue];
CGRectnewFrame = webView.frame;
newFrame.size.height= webViewHeight;
webView.frame= newFrame;
}

Set the height of UIWebView to a minimum, then use sizeThatFits to return exactly the right size


-(void)webViewDidFinishLoad:(UIWebView*)webVie{
CGSize actualSize = [webView sizeThatFits:CGSizeZero];
CGRect newFrame = webView.frame;
newFrame.size.height = actualSize.height;
webView.frame = newFrame;
}

// Method 4. Iterate over the webview subview to get the UIWebDocumentView height, which is the actual height


-(void)webViewDidFinishLoad:(UIWebView *)webView{
CGFloat webViewHeight = 0.0f;
if([webView.subviews count] > 0)
{
UIView *scrollerView = webView.subviews[0];
if([scrollerView.subviews count] >
0)
{
UIView *webDocView = scrollerView.subviews.lastObject;
if ([webDocView isKindOfClass:[NSClassFromString(@UIWebDocumentView)class]])
{
webViewHeight = webDocView.frame.size.height;// Gets the height of the document 
webView.frame=webDocView.frame;
// update UIWebView  The height of the 
}
}
}
}

Related articles: