[英]How to calculate height of html string before loading into webview in ios 7?
I want to find the height of html string that is coming from webservice. 我想找到来自webservice的html字符串的高度。 Kindly suggest me with the best solution.
请建议我最好的解决方案。
Thanks in Advance 提前致谢
A bit of a workaround to this would be to load the HTML into an NSAttributedString
and get it's height. 对此的一些解决方法是将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;
I haven't tried this with varied HTML so YMMV. 我没有尝试过各种各样的HTML,所以YMMV。
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
float contentSizeForWebview = webView.scrollView.contentSize.height;
}
You can calculat hight using following funtion: 您可以使用以下功能计算高度:
-(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;
}
So you can get hegith by: 所以你可以通过以下方式获得成功:
CGSize HTMLTextHeight =[self GetTextHightForLable:yourString];
CGFloat height = HTMLTextHeight.size.height;
I had to deal with web view height calculation issue before. 我之前不得不处理Web视图高度计算问题。 What I can tell here is: it's impossible to calculate the height of a HTML string without loading it to an web view and see its actual height after being rendered.
我在这里可以看出:如果不将HTML字符串加载到Web视图并在渲染后查看其实际高度,则无法计算HTML字符串的高度。 There is another thing you may need to think about is the possibility of having Javascript or hidden elements inside the HTML content.
您可能需要考虑的另一件事是在HTML内容中包含Javascript或隐藏元素的可能性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.