Display HTML text in UILabel iphone

前端 未结 11 2002
借酒劲吻你
借酒劲吻你 2020-12-02 14:39

I am getting a HTML Response from a webservice Below is the HTML I am getting in response

TopicGud mrng.

\\n
11条回答
  •  余生分开走
    2020-12-02 14:57

    Lately I've been dealing with partial HTML snippets and converting them to attributed strings with the ability to add attributes. Here is my version of the extension

    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..

    I call it thus:

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

提交回复
热议问题