【问题标题】:Display html text in uitextview在 uitextview 中显示 html 文本
【发布时间】:2011-01-28 02:02:30
【问题描述】:

如何在 textview 中显示 HTML 文本?

例如,

string <h1>Krupal testing <span style="font-weight:
bold;">Customer WYWO</span></h1>

假设文本是粗体,所以它在 textview 中显示为粗体字符串 但我想显示普通文本。这在 iPhone SDK 中可行吗?

【问题讨论】:

    标签: ios iphone uitextview


    【解决方案1】:

    使用以下适用于 ios 7+ 的代码块。

    NSString *htmlString = @"<h1>Header</h1><h2>Subheader</h2><p>Some <em>text</em></p><img src='http://blogs.babble.com/famecrawler/files/2010/11/mickey_mouse-1097.jpg' width=70 height=100 />";
    NSAttributedString *attributedString = [[NSAttributedString alloc]
              initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding]
                   options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
        documentAttributes: nil
                     error: nil
    ];
    textView.attributedText = attributedString;
    

    【讨论】:

    • 嗨,如何计算文本视图的高度?我不希望文本视图滚动。我使用了 textView.contensize。没用。
    • 如何更改字符串的字体?使用 addAttribute:NSFontAttributeName 似乎重置了所有字体(粗体)。
    • 要更改字体,请将NSAttributedString更改为NSMutableAttributedString并添加[attributedString addAttributes:@{NSFontAttributeName: font} range:NSMakeRange(0, attributedString.length)];
    • 自动调整大小tv.frame = CGRectMake(0, 0, HUGE, 1); [tv sizeToFit];
    • @Durgaprasad 修改字符串的样式,您可以创建可变副本并为其设置属性:NSMutableAttributedString *mString = [[NSMutableAttributedString alloc] initWithAttributedString:attributedString]; [mString addAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]} range:NSMakeRange(0, mString.length)];
    【解决方案2】:

    在 iOS 5-上使用 UIWebView。

    在 iOS 6+ 上,您可以使用 UITextView.attributedString,具体方法请参见 https://stackoverflow.com/a/20996085


    还有一个 undocumented -[UITextView setContentToHTMLString:] 方法。如果您想提交到 AppStore,请不要使用此选项。

    【讨论】:

    • App会因为使用无证方法而被拒绝......我已经体验过了。
    • 这个方法在 ios 7 中还没有记录吗?
    • @Ajeet 如果您在 developer.apple.com 中找不到它,那么它是无证的。
    • 嗨,如何计算文本视图的高度?我不希望文本视图滚动。我使用了 textView.contensize。没用。
    • 它有效。但我还需要显示 HTML 表格内容。当我尝试时,它只显示 标签的内容。如何显示 HTML 表格内容?
    【解决方案3】:

    对于 Swift 4Swift 4.2:Swift 5

    let htmlString = """
        <html>
            <head>
                <style>
                    body {
                        background-color : rgb(230, 230, 230);
                        font-family      : 'Arial';
                        text-decoration  : none;
                    }
                </style>
            </head>
            <body>
                <h1>A title</h1>
                <p>A paragraph</p>
                <b>bold text</b>
            </body>
        </html>
        """
    
    let htmlData = NSString(string: htmlString).data(using: String.Encoding.unicode.rawValue)
    
    let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html]
    
    let attributedString = try! NSAttributedString(data: htmlData!, options: options, documentAttributes: nil)
    
    textView.attributedText = attributedString
    

    对于 Swift 3

    let htmlString = """
        <html>
            <head>
                <style>
                    body {
                        background-color : rgb(230, 230, 230);
                        font-family      : 'Arial';
                        text-decoration  : none;
                    }
                </style>
            </head>
            <body>
                <h1>A title</h1>
                <p>A paragraph</p>
                <b>bold text</b>
            </body>
        </html>
        """
    
    let htmlData = NSString(string: htmlString).data(using: String.Encoding.unicode.rawValue)
    
    let attributedString = try! NSAttributedString(data: htmlData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
    
    textView.attributedText = attributedString
    

    【讨论】:

    • 有没有办法将外部css添加到html属性字符串@pableiros
    • @Mansuu.... 你必须从你的包中读取 css 文件:let path = Bundle.main.path(forResource: "styles", ofType: "css"),获取内容 let content = try! String(contentsOfFile: path!, encoding: String.Encoding.utf8) 并将其添加到 html 字符串中
    • 谢谢@pableiros 它有效,但不是我想要的方式。我的外部 css 导入 bootstrap.min.css。当我通过获取它的内容将 css 应用于 UItextView 时,它不起作用。
    • 非常感谢它对我的 swift 3 有用 :) 继续努力
    【解决方案4】:

    BHUPI 的回答是正确的,但是如果您想将 UILabel 或 UITextView 中的自定义字体与 HTML 内容结合起来,您需要稍微更正一下您的 html:

    NSString *htmlString = @"<b>Bold</b><br><i>Italic</i><p> <del>Deleted</del><p>List<ul><li>Coffee</li><li type='square'>Tea</li></ul><br><a href='URL'>Link </a>";
    
    htmlString = [htmlString stringByAppendingString:@"<style>body{font-family:'YOUR_FONT_HERE'; font-size:'SIZE';}</style>"];
    /*Example:
    
     htmlString = [htmlString stringByAppendingString:[NSString stringWithFormat:@"<style>body{font-family: '%@'; font-size:%fpx;}</style>",_myLabel.font.fontName,_myLabel.font.pointSize]];
    */
     NSAttributedString *attributedString = [[NSAttributedString alloc]
                          initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding]
                               options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                    documentAttributes: nil
                                 error: nil
                ];
    textView.attributedText = attributedString;
    

    您可以在下图中看到不同之处:

    【讨论】:

    • 你能把苹果的系统字体放在这里吗?
    • 我想添加外部css,我该怎么做? @大卫
    【解决方案5】:

    您可以查看 OHAttributedLabel 类,我使用这些类来克服我的 textField 的此类问题。在此,他们重写了 drawRect 方法以获得所需的样式。

    https://github.com/AliSoftware/OHAttributedLabel

    【讨论】:

    • OHAttributedLabel如何显示ul li标签?
    【解决方案6】:

    我的第一个反应是在 iOS 7 明确支持在通用控件中显示属性字符串之前做出的。您现在可以将UITextView 中的attributedText 设置为使用HTML 内容创建的NSAttributedString

    -(id)initWithData:(NSData *)data options:(NSDictionary *)options documentAttributes:(NSDictionary **)dict error:(NSError **)error 
    

    - initWithData:options:documentAttributes:error: (Apple Doc)

    原始答案,留作历史:

    除非您使用UIWebView,否则您的解决方案将直接依赖于CoreText。正如 ElanhiraiyanS 所指出的,一些开源项目已经出现,以简化富文本渲染。我会推荐 NSAttributedString-Additions-For-HTML编辑: 该项目已被 DTCoreText 取代),它具有从 HTML 生成和显示属性字符串的类。

    【讨论】:

      【解决方案7】:

      BHUPI 的回答很适合我。

      转成swift的代码如下:

      注意“allowLossyConversion: false”

      如果你将值设置为true,它将显示纯文本。

      let theString = "<h1>H1 title</h1><b>Logo</b><img src='http://www.aver.com/Images/Shared/logo-color.png'><br>~end~"
      
              let theAttributedString = try! NSAttributedString(data: theString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!,
                  options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                  documentAttributes: nil)
      
              UITextView_Message.attributedText = theAttributedString
      

      【讨论】:

      • NSUnicodeStringEncoding 是正确的,因为 NSString 是 Unicode 编码的,而不是 UTF8。如果是 CJK 字符,您将无法得到正确答案。
      【解决方案8】:

      对于 Swift3

          let theString = "<h1>H1 title</h1><b>Logo</b><img src='http://www.aver.com/Images/Shared/logo-color.png'><br>~end~"
      
          let theAttributedString = try! NSAttributedString(data: theString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!,
              options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
              documentAttributes: nil)
      
          UITextView_Message.attributedText = theAttributedString
      

      【讨论】:

        【解决方案9】:

        在某些情况下 UIWebView 是一个很好的解决方案。因为:

        • 它显示表格、图像和其他文件
        • 速度很快(与 NSAttributedString 相比:NSHTMLTextDocumentType)
        • 开箱即用

        使用 NSAttributedString 可能会导致崩溃,如果 html 很复杂或包含表格 (so example)

        为了将文本加载到 web 视图,您可以使用以下 sn-p(只是示例):

        func loadHTMLText(_ text: String?, font: UIFont) {
                let fontSize = font.pointSize * UIScreen.screens[0].scale
                let html = """
                <html><body><span style=\"font-family: \(font.fontName); font-size: \(fontSize)\; color: #112233">\(text ?? "")</span></body></html>
                """
                self.loadHTMLString(html, baseURL: nil)
            }
        

        【讨论】:

          【解决方案10】:

          您还可以使用另一种方式。 Three20 库提供了一种方法,通过它我们可以构造样式化的 textView。你可以在这里获取图书馆:http://github.com/facebook/three20/

          TTStyledTextLabel 类有一个名为 textFromXHTML 的方法:我想这可以达到目的。但是在只读模式下是可能的。我认为它不允许编写或编辑 HTML 内容。

          还有一个问题可以帮助你解决这个问题:HTML String content for UILabel and TextView

          希望对你有帮助。

          【讨论】:

            【解决方案11】:

            NSDoc 将字符串中的文本文件保存到 html 文件中,然后同时将其加载到与 UITextView 位于同一位置的 webview 中。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-02-28
              • 2014-07-22
              • 2016-04-24
              • 1970-01-01
              • 1970-01-01
              • 2014-10-30
              • 1970-01-01
              • 2021-09-30
              相关资源
              最近更新 更多