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

mah*_*esh 7 iphone ios ios7

我想找到来自webservice的html字符串的高度.请建议我最好的解决方案.

提前致谢

Ste*_*ord 4

对此的一个解决方法是将 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;
Run Code Online (Sandbox Code Playgroud)

我还没有尝试过使用不同的 HTML,所以 YMMV。