iOS: Resize UIWebView after didFinishLoad (content should fit without scrolling)

自作多情 提交于 2019-12-03 15:37:09
John Stephen

The UIScrollView property is available for UIWebView starting in iOS 5. You can use that to resize your view by implementing the webViewDidFinishLoad: message in your delegate, like this:

-(void)webViewDidFinishLoad:(UIWebView *)webView {
    CGRect newBounds = webView.bounds;
    newBounds.size.height = webView.scrollView.contentSize.height;
    webView.bounds = newBounds;
}
zero3nna

Have you tried: this answer?

[Edit]

Some guys say this is working:

- (void)webViewDidFinishLoad:(UIWebView *)webView {

// Change the height dynamically of the UIWebView to match the html content
CGRect webViewFrame = webView.frame;
webViewFrame.size.height = 1;
webView.frame = webViewFrame;
CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
webViewFrame.size = fittingSize;
// webViewFrame.size.width = 276; Making sure that the webView doesn't get wider than 276 px
webView.frame = webViewFrame;

float webViewHeight = webView.frame.size.height;
}

This is untested by me but 70 people voted ^ to this answer and its recommend to set sizeTahtFits:CGSizeZero like a reset of your frame.size

and some people use JavaScript to fix this:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *string = [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"body\").offsetHeight;"];
CGFloat height = [string floatValue] + 8;
CGRect frame = [_webView frame];
frame.size.height = height;
[_webView setFrame:frame];

if ([[self delegate] respondsToSelector:@selector(webViewController:webViewDidResize:)])
{
    [[self delegate] webViewController:self webViewDidResize:frame.size];
}
}

as answered by john and eric above, this piece of code works.

-(void)webViewDidFinishLoad:(UIWebView *)webView {
    CGRect newBounds = webView.bounds;
    newBounds.size.height = webView.scrollView.contentSize.height;
    webView.bounds = newBounds;
}

however while trying with this code i found out it returns me with a proper webview but improper origin, if thats the case for anyone, simply reset with this code

webView.frame=CGRectMake(webView.frame.origin.x, webView.center.y, webView.frame.size.width, webView.frame.size.height);

The y-axis is set and you get the webView as you wanted.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!