html - 如何在 UIWebView 中水平和垂直居中 HTML 字符串

标签 html ios css objective-c

我得到了 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/

相关文章:

css - 带有叠加 CSS 的背景图像

python - HTML 新手问题 : Colored Background for Characters in Django HttpResponse

ios - 将 subview 作为背景添加到导航栏

iOS8.1 Core-Data轻量级+重量级迁移

html - CSS:希望文本在同一行

css - 图像 CSS 不会从 MOBI KindleGen 更改为 iPad kindle

jquery - 如何根据内容选择元素?

html - box-shadow 不遵循 z-index 顺序

html - 防止列表项填充在水平列表中换行

iphone - 虚拟 LAN 上的推送通知