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

问题描述 投票:1回答:2

在我的应用程序中,我想从服务器获取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标签指的是另一个类。

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

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

     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    
}
html swift xcode
2个回答
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

希望,这段代码可以帮到你


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    
 } 
© www.soinside.com 2019 - 2024. All rights reserved.