Display HTML text in UILabel iphone

前端 未结 11 1968
借酒劲吻你
借酒劲吻你 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:55

    Swift 4: version

    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: version

    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: version

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

    use it as:

    label.attributedText = yourStringVar.htmlAttributedString()
    

提交回复
热议问题