如何在ios 7加载到webview之前计算html字符串的高度



我想找到来自webservice的html字符串的高度。请告诉我最好的解决办法。

Thanks in Advance

一个解决这个问题的方法是将HTML加载到NSAttributedString中并获取它的高度。

NSAttributedString *text = [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUTF8StringEncoding]
                                                            options:@{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
                                                                      NSCharacterEncodingDocumentAttribute : @(NSUTF8StringEncoding)}
                                                 documentAttributes:nil
                                                              error:nil]; // make sure to check for error in a real app
// Then get the bounding rect based on a known width
CGRect textFrame = [text boundingRectWithSize:CGSizeMake(someKnownWidth, CGFLOAT_MAX)
                                      options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                      context:nil];
CGFloat height = textFrame.size.height;

我还没有尝试过这个不同的HTML所以YMMV.

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    float contentSizeForWebview = webView.scrollView.contentSize.height;
}

可以使用下面的函数来计算高度:

-(CGSize)GetTextHightForLable:(NSString*)strText
{
    UILabel *gettingSizeLabel = [[UILabel alloc] init];
    gettingSizeLabel.font = [UIFont fontWithName:@"GillSans-Light" size:13.0f]; // set same fond and size that used in your html string
    gettingSizeLabel.text = strText;
    gettingSizeLabel.numberOfLines = 0;
    CGSize maximumLabelSize = CGSizeMake(270, MAXFLOAT); // 270 is a width you must set same width of you webview this width will be as per your requirement
    CGSize expectedSize = [gettingSizeLabel sizeThatFits:maximumLabelSize];
    return expectedSize;
}

所以你可以得到hegith:

 CGSize HTMLTextHeight =[self GetTextHightForLable:yourString];
 CGFloat height = HTMLTextHeight.size.height;

我以前不得不处理网页视图高度计算问题。我能告诉你的是:如果不将HTML字符串加载到web视图中并在渲染后查看其实际高度,就不可能计算出它的高度。您可能需要考虑的另一件事是在HTML内容中包含Javascript或隐藏元素的可能性。

最新更新