具有 html 数据的 uiwebview 的动态高度

Dynamic height for uiwebview with html data

作为我的应用程序的一部分,我需要在 uiwebview 中显示 html 内容以及包含 <ul><li> 标签的数据 我正在使用属性字符串来计算高度webview 但每当数据包含此列出的内容时,它都会计算出不正确的高度我在 lat 2 天里遇到了这个问题,当列表包含短文本数据时,它会 returns 更少的高度,当它出现时我的内容会被遗漏ipad 由于 webview 的宽度过大,问题变得最严重。

 NSMutableAttributedString *htmlString1 =
        [[NSMutableAttributedString alloc] initWithData:[[self.doctorDetail objectForKey:@"Description"] dataUsingEncoding:NSUTF8StringEncoding]
                                                options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                          NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]}
                                     documentAttributes:NULL error:nil];

        [htmlString1 addAttributes:attrsDictionary range:NSMakeRange(0, htmlString1.length)];
        CGSize discriptionsize = CGSizeMake(self.discriptionLabel.frame.size.width, FLT_MAX);


        CGRect textRect = [htmlString1 boundingRectWithSize:discriptionsize options:NSStringDrawingUsesLineFragmentOrigin context:nil];

CGSize expectedLabelSize = CGSizeMake(textRect.size.width, textRect.size.height);
[self.discriptionLabel setFrame:CGRectMake(self.discriptionLabel.frame.origin.x, self.doctorImage.frame.origin.y+self.doctorImage.frame.size.height+5, self.discriptionLabel.frame.size.width, expectedLabelSize.height+10)];

你可能应该这样做:

- (void)viewDidLoad
{
    [super viewDidLoad];
    webview.delegate = self;
    [webview loadHTMLString:@"<div id='foo' style='background: red'>The quick brown fox jumped over the lazy dog.</div>" baseURL:nil];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *output = [webview stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"foo\").offsetHeight;"];
    NSLog(@"height: %@", output);
}

感谢此处提供的答案:

我明白了,

刚刚将 <li> 替换为 <br>,然后将其设置为属性字符串

   valueString = [valueString stringByReplacingOccurrencesOfString:@"<li>" withString:@"<br>"];