简体   繁体   中英

Set dynamic height of webview depending on the content iphone

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.

Thanx in advance.

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: .

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM