将HTML转换为带有标签的字符串

时间:2018-09-03 06:45:43

标签: html swift xcode

在我的应用程序中,我想从服务器获取HTML格式的文本,并将其转换为字符串以使用UILabel在另一个视图中显示。要将HTML转换为字符串,我正在使用此扩展名:

extension Data{
var html2AttributedString: NSAttributedString?{
    do{
        return try NSAttributedString(data: self, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
    }catch{
        print("error", error)
        return nil
    }
}

  var html2String: String {
    return html2AttributedString?.string ?? ""
  }
}

extension String{
   var html2AttributedString: NSAttributedString? {
    return Data(utf8).html2AttributedString
  }
  var html2String: String{
    return html2AttributedString?.string ?? ""
  }
}

从数组中调用字符串,如下所示:

text.detailText = textArray[0].html2String

但是,当数据显示在屏幕上时,字符串仅显示为纯文本,没有HTML标记。我需要在扩展程序中进行哪些修改才能正确显示带有受影响标签的文本?

编辑:text中的text.detailText标签是指另一个类。

在上下文中,它看起来像这样:

上下文中的文本变量引用了另一个类。在上下文中看起来像这样:

     if let otherClass = segue.destination as? otherClass {
         otherClass.detailText = textArray[0].html2String    
     } 

另一个类如下:

class otherClass:UIViewController {

var data: Data?

@IBOutlet weak var otherDetail: UILabel!

var detailText: String =  ""    
override func viewDidLoad() {
    super.viewDidLoad()
    otherDetail?.text = detailText    
}

2 个答案:

答案 0 :(得分:0)

您可以看到这个简单的示例,它可以正常工作。我只是设置了标签attributedText字段

let htmlString = """
<p><b>This text is bold</b></p>
<p><i>This text is italic</i></p>
<p>This is<sub> subscript</sub> and <sup>superscript</sup></p>
"""

let attributedString = htmlString.data(using: .utf8).flatMap { data -> NSAttributedString? in
    return try? NSAttributedString(
        data: data,
        options: [
            .documentType: NSAttributedString.DocumentType.html,
            .characterEncoding: String.Encoding.utf8.rawValue
        ],
        documentAttributes: nil)
}
guard let attrString = attributedString else { return }
yourLabel.numberOfLines = 0
yourLabel.attributedText = attrString

希望,这段代码对您有帮助

答案 1 :(得分:0)

为了呈现html标签,您应该使用属性字符串:

 //detailText should be of type NSAttributedString
 detailedText : NSAttributedString!

 //replace html2String with html2AttributedString
 if let otherClass = segue.destination as? otherClass {
     otherClass.detailText = textArray[0].html2AttributedString    
 } 

 //and in the otherClass replace .text with .
 var data: Data?

 @IBOutlet weak var otherDetail: UILabel!

 var detailText: NSAttributedString!    
 override func viewDidLoad() {
     super.viewDidLoad()
     otherDetail?.attributedText = detailText    
 }