1

I have the following code:

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 1)];
[webView loadHTMLString:[input objectForKey:@"htmlContent"] baseURL:nil];
CGSize size = [webView sizeThatFits:CGSizeMake(kWidth, FLT_MAX)];
webView.frame = CGRectMake(0, 0, kWidth, size.height);
NSLog(@"%@",NSStringFromCGRect(webView.frame));
NSLog(@"%@",NSStringFromCGSize(size));

The idea was taken from this answer and as OP mentions before using sizeThatFits there is a minimum size chosen i.e. 1. The output of on the screen is as follows:

{{0, 0}, {768, 1}}
{768, 1}

In other words, the height doesn't get modified and what ever value I will pick instead of 1, it will remain as the height of my view. What exactly am i doing wrong?

Community
  • 1
  • 1
Alexandru Barbarosie
  • 2,952
  • 3
  • 24
  • 46

1 Answers1

4

Because loadHTMLString is async, your sizeThatFits method will be called before the actual html is loaded and rendered.

What I suggest is one, implement UIWebViewDelegate protocol

webView.delegate = self;

and then

-(void)webViewDidFinishLoad:(UIWebView *)webView {
    CGSize size = [webView sizeThatFits:CGSizeMake(kWidth, FLT_MAX)];
    webView.frame = CGRectMake(0, 0, kWidth, size.height);
}

NOTE : I don't see anywhere in your code where you are adding your webview as a subview, but I am assuming you are

  • 1
    +1. Also, if your HTML string contains multiple frames, you might want to count those in `webViewDidStartLoad:`, decrease the count in `webViewDidFinishLoad:`, and update the view when you decrease to `0`. – Aaron Brager Aug 26 '14 at 17:59
  • The `sizeThatFits` method returns a `CGSize` so in your example nothing would happen. – inorganik Oct 01 '14 at 23:29
  • You are right. I was just saying where he could then use the method.. but i'll edit with the usage of it – Marc-Alexandre Bérubé Oct 02 '14 at 14:14