HTML гиперссылка на NSAttributedString не оформлена - PullRequest
0 голосов
/ 15 апреля 2020

Я пытаюсь создать NSAttributedString из заданной строки HTML, с абзацем и гиперссылкой. Все хорошо, кроме стилизации гиперссылки. Мой код стиля выглядит так:

func htmlAttributed() -> NSAttributedString? {
    do {
        let htmlCSSString = "<style>" +
            "* {" +
                "font-size: 12px !important;" +
                "color: #9D9B98 !important;" +
            "}" +
            "p" +
            "{" +
                "font-size: 12px !important;" +
                "color: #9D9B98 !important;" +
                "font-family: Helvetica !important;" +
            "}" +
            "a" +
            "{" +
                "font-size: 12px !important;" +
                "color: hotpink !important;" +
                "font-family: Helvetica !important;" +
            "}" +
            "a:link" +
            "{" +
            "text-decoration: none !important;" +
            "color: hotpink !important;" +
            "}" +
            "a:visited" +
            "{" +
            "text-decoration: none !important;" +
            "}" +
            "</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 {
        print("error: ", error)
        return nil
    }
}

, и он дает отличный результат, когда я открываю его на веб-сайте. Но перевод в NSAttributedString работает только для метки p, а не для гиперссылки.

Для тестирования я использую эту часть кода

<p>This is not a link <b><a class='test' href='test' target='_blank'>This is a link</a></b></p>

На игровой площадке w3 c У меня есть: enter image description here

Вкл iPhone У меня есть:

enter image description here

1 Ответ

0 голосов
/ 15 апреля 2020

Если вы используете UILabel, попробуйте вместо этого UITextView и измените цвета ссылок, используя linkTextAttributes. Таким образом, ваши ссылки также будут доступны.

textView.linkTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.systemPink]

enter image description here

...