swift html字符串转富文本

2022-01-06  本文已影响0人  轻轻语焉

func attributedString(font: UIFont = UIFont.systemFont(ofSize: 14)) -> NSMutableAttributedString? {

        guard let data = self.data(using: String.Encoding.utf8,

            allowLossyConversion: false) else { return nil }

        let options: [NSAttributedString.DocumentReadingOptionKey : Any] = [

            NSAttributedString.DocumentReadingOptionKey.characterEncoding : String.Encoding.utf8.rawValue,

            NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html,

        ]

        let htmlString = try? NSMutableAttributedString(data: data, options: options, documentAttributes: nil)

        // Removing this line makes the bug reappear

        htmlString?.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.clear, range: NSMakeRange(0, 1))

        htmlString?.addAttributes([NSAttributedString.Key.font : font], range: NSMakeRange(0, htmlString?.length ?? 0 ))

        return htmlString

    }

上一篇 下一篇

猜你喜欢

热点阅读