我得到了 UTF-8 格式的 HTML 字符串,我需要在 webView 中显示它。但我希望字符串在 UIWebView 中水平和垂直居中
最佳答案
好吧,我测试并制定了一个可行的解决方案。那么这就是我如何获得所需的输出。那么函数 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);
}
关于html - 如何在 UIWebView 中水平和垂直居中 HTML 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39818895/