【问题标题】:Display HTML text in UILabel iphone在 UILabel iphone 中显示 HTML 文本
【发布时间】:2013-03-30 03:08:39
【问题描述】:

我正在从网络服务获取 HTML 响应 以下是我收到的 HTML 回复

<p><strong>Topic</strong>Gud mrng.</p>
\n<p><strong>Hello Everybody</strong>: How are you.</p>
\n<p><strong>I am fine</strong>: 1 what about you.</p>

我需要在 UILabel 中显示文本。

请帮忙

【问题讨论】:

  • 使用禁用滚动的 textView ;)

标签: html xcode text uilabel


【解决方案1】:

有时我们需要使用 UILabel 在屏幕上显示 HTML 内容。如何在 UILabel 中显示 HTML 内容我们在这篇文章中看到。让我们开始并实现它。

目标 C:

NSString * htmlString = @"<html><body> <b>  HTML in UILabel is here…. </b> </body></html>";
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString
dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute:
NSHTMLTextDocumentType } documentAttributes:nil error:nil];
UILabel * yourLabel = [[UILabel alloc] init];
yourLabel.attributedText = attrStr;

斯威夫特:

var htmlString = “<html><body> <b>  HTML in UILabel is here…. </b> </body></html>”
var attrStr: NSAttributedString? = nil
do {
 if let data = htmlString.data(using: .unicode) {
 attrStr = try? NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
 }
} catch {
}
var yourLabel = UILabel()
yourLabel.attributedText = attrStr

参考:https://medium.com/@javedmultani16/html-text-in-uilabel-ios-f1e0760bcac5

【讨论】:

    【解决方案2】:

    Swift 3 中的上述答案:

        var str = "<html> ... some html ... </html>"
    
        let htmlStringData = NSString(string: str).data(using: String.Encoding.utf8.rawValue)
        let html = htmlStringData
    
        do {
            let htmlAttrString = try? NSAttributedString(
                    data: html!,
                    options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                    documentAttributes: nil
            )
            agreementText.attributedText = htmlAttrString
        } catch {
            print("An error occured")
        }
    

    【讨论】:

      【解决方案3】:
      **// Swift 4 compatible | with setting of colour and font options:**
      
      // add following extension to String:
      
              func htmlAttributed(family: String?, size: CGFloat, color: UIColor) -> NSAttributedString? {
      
                      let sizeInPx = (size * 0.75)
      
                      do {
                        let htmlCSSString = "<style>" +
                          "html *" +
                          "{" +
                          "font-size: \(sizeInPx)pt !important;" +
                          "color: \(color.hexString ?? "#000000") !important;" +
                          "font-family: \(family ?? "SFUIText-Regular"), SFUIText !important;" +
                        "}</style> \(self)"
      
                        guard let data = htmlCSSString.data(using: String.Encoding.utf8) else {
                          return nil
                        }
      
                        return try NSAttributedString(data: data,
                                                      options: [.documentType: NSAttributedString.DocumentType.html,
                                                                .characterEncoding: String.Encoding.utf8.rawValue],
                                                      documentAttributes: nil)
                      } catch {
                        print("error: ", error)
                        return nil
                      }
                    }
      
              // add following extension to UIColor:
      
              extension UIColor{
      
                var hexString:String? {
                  if let components = self.cgColor.components {
                    let r = components[0]
                    let g = components[1]
                    let b = components[2]
                    return  String(format: "%02X%02X%02X", (Int)(r * 255), (Int)(g * 255), (Int)(b * 255))
                  }
                  return nil
                }
              }
      
          // Sample Use:
      
          yourLabel.attributedText = locationTitle.htmlAttributed(family: yourLabel.font.fontName,
                                                                                 size: yourLabel.font.pointSize,
                                                                                 color: yourLabel.textColor)
      

      【讨论】:

        【解决方案4】:

        斯威夫特 4

        我宁愿建议使用可失败的便利初始化来扩展 NSAttributedString。 String 本质上不负责制作 NSAttributedString

        extension NSAttributedString {
             convenience init?(html: String) {
                guard let data = html.data(using: String.Encoding.unicode, allowLossyConversion: false) else {
                    return nil
                }
                guard let attributedString = try? NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) else {
                    return nil
                }
                self.init(attributedString: attributedString)
            }
        }
        label.attributedText = NSAttributedString(html: "<span> Some <b>bold</b> and <a href='#/userProfile/uname'> Hyperlink </a> and so on </span>")
        

        【讨论】:

          【解决方案5】:

          Swift 4:版本

          extension String {
              func htmlAttributedString() -> NSAttributedString? {
                  guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
                  guard let html = try? NSMutableAttributedString(
                      data: data,
                      options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
                      documentAttributes: nil) else { return nil }
                  return html
              }
          }
          

          Swift 3:版本

          extension String {
          func htmlAttributedString() -> NSAttributedString? {
              guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
              guard let html = try? NSMutableAttributedString(
                  data: data,
                  options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                  documentAttributes: nil) else { return nil }
              return html
              }
          }
          

          Swift 2:版本

          extension String {
                  func htmlAttributedString() -> NSAttributedString? {
                      guard let data = self.dataUsingEncoding(NSUTF16StringEncoding, allowLossyConversion: false) else { return nil }
                      guard let html = try? NSMutableAttributedString(
                        data: data, 
                        options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], 
                        documentAttributes: nil) else { return nil }
                      return html
                  }
          }
          

          将其用作:

          label.attributedText = yourStringVar.htmlAttributedString()
          

          【讨论】:

          • 我的字符串是:“Process Specialist”。 Bt 它的回报与我发送给您的分机的相同。
          【解决方案6】:

          最近我一直在处理部分 HTML sn-ps 并将它们转换为具有添加属性的属性字符串。这是我的扩展版本

          import Foundation
          import UIKit
          
          extension String {
            func htmlAttributedString(attributes: [String : Any]? = .none) -> NSAttributedString? {
              guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return .none }
              guard let html = try? NSMutableAttributedString(
                data: data,
                options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                documentAttributes: .none) else { return .none }
          
          
              html.setAttributes(attributes, range: NSRange(0..<html.length))
          
              return html
            }
          }
          

          我这样称呼它:

          let attributes = [
            NSForegroundColorAttributeName: UIColor.lightGray,
            NSFontAttributeName : UIFont.systemFont(ofSize: 12).traits(traits: .traitItalic)
          ]
          
          label?.attributedText = partialHTMLString.htmlAttributedString(attributes: attributes)
          

          【讨论】:

            【解决方案7】:

            Swift 3 中的上述答案:

            func htmlAttributedString() -> NSAttributedString? {
                guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
                guard let html = try? NSMutableAttributedString(
                    data: data,
                    options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                    documentAttributes: nil) else { return nil }
                return html
            }
            

            【讨论】:

              【解决方案8】:

              这里是 swift 2 版本:

                  let htmlStringData = NSString(string: "<strong>Your HTML String here</strong>").dataUsingEncoding(NSUTF8StringEncoding)
                  guard let html = htmlStringData else { return }
              
                  do {
                      let htmlAttrString = try NSAttributedString(data: html, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
                      yourLabel.attributedText = htmlAttrString
                  } catch {
                      print("An error occured")
                  }
              

              【讨论】:

                【解决方案9】:

                您可以通过使用属性文本在没有任何第三方库的情况下完成此操作。我相信它确实接受 HTML 片段,就像你得到的那样,但你可能希望将它包装在一个完整的 HTML 文档中,以便你可以指定 CSS:

                static NSString *html =
                    @"<html>"
                     "  <head>"
                     "    <style type='text/css'>"
                     "      body { font: 16pt 'Gill Sans'; color: #1a004b; }"
                     "      i { color: #822; }"
                     "    </style>"
                     "  </head>"
                     "  <body>Here is some <i>formatting!</i></body>"
                     "</html>";
                
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 200)];
                NSError *err = nil;
                label.attributedText =
                    [[NSAttributedString alloc]
                              initWithData: [html dataUsingEncoding:NSUTF8StringEncoding]
                                   options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                        documentAttributes: nil
                                     error: &err];
                if(err)
                    NSLog(@"Unable to parse label text: %@", err);
                

                不简洁,但你可以通过向 UILabel 添加一个类别来收拾烂摊子:

                @implementation UILabel (Html)
                
                - (void) setHtml: (NSString*) html
                    {
                    NSError *err = nil;
                    self.attributedText =
                        [[NSAttributedString alloc]
                                  initWithData: [html dataUsingEncoding:NSUTF8StringEncoding]
                                       options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                            documentAttributes: nil
                                         error: &err];
                    if(err)
                        NSLog(@"Unable to parse label text: %@", err);
                    }
                
                @end
                

                [someLabel setHtml:@"Be <b>bold!</b>"];
                

                【讨论】:

                • 此方法无法识别
                  标签。它只是删除
                  标签
                  之前的元素
                • 为了使
                  工作,您需要将 UILabel 的 numberOfLines 属性设置为 0:self.titleLbl.numberOfLines = 0;
                • 这样做的时候还能设置字体和颜色吗? self.attributedText = [[NSAttributedString alloc] initWithData: [html dataUsingEncoding:NSUTF8StringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue" size:12.0], NSForegroundColorAttributeName: [UIColor redColor] } documentAttributes: nil error: &amp;err]; 好像不行
                • @DemandedCross 我知道你的评论很古老,但对其他人来说,我认为你需要使用 HTML 颜色代码而不是 UIColor
                • [html dataUsingEncoding:NSUTF16StringEncoding] 在处理 CJK 字符时是首选,因为 NSString 是 UTF16 编码的,即 NSUnicodeStringEncoding
                【解决方案10】:

                使用 RTLabel 库转换 HTML 文本。我已经用过好几次了。有用。这是库的链接和示例代码。

                https://github.com/honcheng/RTLabel.

                希望我能帮上忙。

                【讨论】:

                • 我面临的一个问题是,在我旋转设备时在UITableViewCell 中加载文本后,标签文本变得更宽。同样的情况也发生在portrait 的景观中。标签文本变窄。为什么?有什么解决方法吗?
                【解决方案11】:

                发件人:https://stackoverflow.com/a/5581178/237838


                将 HTML 转换为纯文本 Download 文件

                并使用

                stringByConvertingHTMLToPlainText 函数在您的NSString


                您可以使用DTCoreText(以前称为 NSAttributedString Additions for HTML)。

                【讨论】:

                • DTCoreText build 显示编译时错误。 'DTHTMLParser.h' file not found。有什么想法吗?
                • DTCoreText 以前不称为NSAttributedString
                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2021-07-24
                相关资源
                最近更新 更多