【问题标题】:How to centre a HTML string both horizontally and vertically in a UIWebView如何在 UIWebView 中水平和垂直居中 HTML 字符串
【发布时间】:2018-10-07 17:51:39
【问题描述】:

我得到了 UTF-8 格式的 HTML 字符串,我需要在 webView 中显示它。但我希望字符串在 UIWebView 中水平和垂直居中

【问题讨论】:

    标签: html ios css objective-c


    【解决方案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);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-08
      • 2011-09-04
      • 1970-01-01
      • 2019-07-19
      • 2015-08-29
      相关资源
      最近更新 更多