在UITextView中,我可以将控件的高度调整为它的内容,如下所示:

CGRect frame = textView.frame;
frame.size.height = textView.contentSize.height;
textView.frame = frame;

但是我想改用UIWebView来显示富文本。 UIWebVie的内容是:
NSString *myDescriptionHTML = [NSString stringWithFormat:@"<html> \n"
                                  "<head> \n"
                                  "<style type=\"text/css\"> \n"
                                  "body {font-family: \"%@\"; font-size: %@; }\n"
                                  "</style> \n"
                                  "</head> \n"
                                  "<body>%@</body> \n"
                                  "</html>", @"helvetica",
                                  [NSNumber numberWithInt:12], @"yadayadayada..."];
[webView loadHTMLString:myDescriptionHTML baseURL:nil];

因此,UIWebView只包含纯文本。如何获得与上述UITextView代码类似的结果?

最佳答案

尽管从理论上讲JavaScript方法提供了

- (void)webViewDidFinishLoad:(UIWebView *)webview
    CGRect oldBounds = [[self webview] bounds];
    CGFloat height = [[webview stringByEvaluatingJavaScriptFromString:@"document.height"] floatValue];
    [webview setBounds:CGRectMake(oldBounds.x, oldBounds.y, oldBounds.width, height)];
}

应该可以工作(并且似乎对大多数人都可以工作),但对我却没有。我尝试了多种变体,但总是返回与真实内容的高度无关的大小。例如,一个衬板的高度为260或244。不知道为什么(很想知道)。

所以我最终按照this答案中的提示进行了操作:
- (void)webViewDidFinishLoad:(UIWebView *)aWebView {
    CGRect frame = aWebView.frame;
    frame.size.height = 1;
    aWebView.frame = frame;
    CGSize fittingSize = [aWebView sizeThatFits:CGSizeZero];
    frame.size = fittingSize;
    aWebView.frame = frame;

    NSLog(@"size: %f, %f", fittingSize.width, fittingSize.height);
}

我认为JS方式更优雅,但该死,它对我不起作用,无法弄清楚原因,尽管此方法开箱即用。

10-02 08:17
查看更多