简体   繁体   English

如何修复从HTML字符串快速转换NSAttributedString?

[英]How to fix in transform NSAttributedString from html string in swift?

When I convert html string to NSAttributedString, it works well normally but I have a problem in specific cases. 当我将html字符串转换为NSAttributedString时,它可以正常工作,但在特定情况下会出现问题。

func htmlAttributed(family: String?, size: CGFloat, color: UIColor) -> NSAttributedString? {
        do {
            let htmlCSSString = "<style>" +
                "html *" +
                "{" +
                "font-size: \(size)px;" +
                "color: \(color.hex);" +
                "font-family: \(family ?? "Helvetica"), Helvetica;" +
            "}</style> \(self)"

            guard let data = htmlCSSString.data(using: String.Encoding.utf8) else {
                return nil
            }

            return try NSAttributedString(data: data,
                                          options: [.documentType: NSAttributedString.DocumentType.html,
                                                    .characterEncoding: String.Encoding.utf8.rawValue],
                                          documentAttributes: nil)
        } catch {
            return nil
        }
    }

This is my test case html string which has problem. 这是我的测试用例html字符串,有问题。 <b>Hi <i>how are <u>you?</u></i></b>

And it's my result with NSAttributedString. 这是我使用NSAttributedString的结果。 Hi how are you? ,你好吗?

I wanted to get all bold in this sentence but I got only Hi bold string. 我想在这句话中加粗,但只有Hi粗体字串。

测试用例html

Seems to work. 似乎可以工作。 Color was changed to a String type for this quick test. 为了进行此快速测试,将颜色更改为String类型。 Your function was included in a String extension. 您的函数包含在String扩展中。 The following is the call to the function. 以下是对该函数的调用。 Returned attributed string was converted to data, in MS Word format, resulting in the above final sentence, displayed in Word. 返回的属性字符串已转换为MS Word格式的数据,导致以上最后一句话显示在Word中。

var s = "<b>Hi <i>how are <u>you?</u></i></b>"
var attr = s.htmlAttributed(family: nil, size: 20, color: "blue")

var MWdata = attr!.docFormat(from: NSRange(location: 0, length: attr!.length),documentAttributes: [NSAttributedString.DocumentAttributeKey(rawValue: "documentType"):NSAttributedString.DocumentType.docFormat])                  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM