2

I want set dynamic height for webview depending on the dynamic text. I've tried

       [my_webview sizeThatFits:CGSizeZero];

But it didn't work for me. I want to set webview height dynamically.

halfer
  • 19,824
  • 17
  • 99
  • 186
neha
  • 6,327
  • 12
  • 46
  • 78
  • [view sizeThatFits:] doesn't change view size. Try [view sizeToFit] but i'm not sure even this will work for a web view as it resizes depending on subviews, and web view doesn't have any typical subviews. Hence this is a comment and not an answer. – Swapnil Luktuke Jul 21 '10 at 09:56

2 Answers2

3

See my answer to a similar question. The trick is to set the frame of the webView to a minimal height prior to sending -sizeThatFits:.

Community
  • 1
  • 1
Ortwin Gentz
  • 52,648
  • 24
  • 135
  • 213
1

Set up your web view as follows:

- (void)webViewSettings {
    NSString *htmlString = @"Your HTML String";
    NSString* descHtmlString = [NSString stringWithFormat: @"<html><meta name=\"viewport\" content=\"width=300, user-scalable=yes\" /><div style='width:300px' id='ContentDiv'><font face=\"Arial\" size=2.5 color='#702f70'>%@</font></div></html>", htmlString];
    descHtmlString = [descHtmlString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [self.webView loadHTMLString:descHtmlString baseURL:[NSURL URLWithString:@""]];
}

Then implemented UIWebViewDelegate in your interface file and the following method in the implementation file:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
        NSString *contentHeight = [self.descriptionWeb stringByEvaluatingJavaScriptFromString:@"document.getElementById('ContentDiv').offsetHeight"];
        self.descriptionWeb.frame = CGRectMake(10,webView.frame.origin.y, 300, [contentHeight floatValue]);
}
Sujith Thankachan
  • 3,508
  • 2
  • 20
  • 25