我以UTF-8格式获取HTML字符串,我需要在webView中显示它。但我希望字符串在UIWebView
中水平和垂直居中答案 0 :(得分:1)
我测试并制定了一个有效的解决方案。那么这就是我如何实现所需的输出。那么函数calculateHeight是我写的。我遇到了不同的解决方案,但没有一个为垂直居中提供所需的解决方案。 calculateHeight方法返回NSAttributedString的总高度,该高度将在将HTML文本转换为NSAttributedString时生成。此高度值还用于通过提供所需的填充来垂直居中文本。
//subCatTexts.text contains the HTML String
NSString *myHTML = [NSString stringWithFormat:@"<!DOCTYPE html><html><head><style>.center
{padding: %fpx 0;border: 0px solid green;text-align: center;}</style></head><body><div class=\"center\"><p>%@</p></div></body>
</html>",self.webView.frame.size.height/2.0-[self calculateHeight:subCatTexts.text],subCatTexts.text];
[_webView loadHTMLString:myHTML baseURL:nil];
使用的功能在这里定义
- (float) calculateHeight:( NSString *)html
{
const char *c = [html cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:c length:strlen(c)];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSAttributedString *attributedString = [[NSAttributedString alloc]
initWithData: [string dataUsingEncoding:NSUnicodeStringEncoding]
options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
documentAttributes: nil
error: nil
];
//-------------Calculating the height of the attributed String-----
CGFloat width = self.view.frame.size.width; // whatever your desired width is
CGRect rect = [attributedString boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
return (rect.size.height);
}