UILabel 中的 HTML 标签不起作用,而是显示了

问题描述 投票:0回答:1

我有这个 HTML 文本:

"<style>* {font-size: 12pt !important;color: #000000 !important;font-family: Montserrat-Regular !important;}</style>Perform the following steps:<br><u>Option 1:</u><br><p>1) Upon receiving a push notification alert, tap on the push notification to launch BIMB Authenticator</p><p>2) Verify the transaction details and choose \"Approve\"</p><p>3) Complete</p><br><u>Option 2:</u><br><ol><p>1) If you didn’t receive push notification, you may launch BIMB Authenticator</p><p>2) Verify the transaction details and choose \"Approve\"</p><p>3) Complete</p>"

我正在尝试在

UILabel
中正确显示此 HTML 文本。我已将
UILabel
设置为
Attributed
这是我将 String 转换为 HTML 格式的 NSAttributedString 的扩展:

extension String {
    func attributedStringFromHTML() -> NSAttributedString? {
        guard let data = "\(self)"
            .data(using: .utf8, allowLossyConversion: false) else {
            Log.error(category: .transaction, message: "Unable to decode data from html string: %@", self)
            return nil
        }
        
        let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
            .documentType: NSAttributedString.DocumentType.html,
            .characterEncoding: String.Encoding.utf8.rawValue
        ]
        
        if let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) {
            return attributedString
        } else {
            Log.error(category: .transaction,
                      message: "Unable to create attributed string from html string: %@",
                      self)
            return nil
        }
    }
}

这就是结果。正如您所看到的,CSS 样式未显示,并且字体已更改,因此 CSS 可以正常工作。然而,显示的标签并没有给出它们应该提供的效果:

你能帮我吗?谢谢。

html ios swift uilabel nsattributedstring
1个回答
0
投票

我尝试了你的代码,它工作正常。我认为这就是您使用

html string
的方式。尝试将其放在
"""html string here"""
之间。您还可以将
"\(self)"
替换为
self
,因为它已经是一个字符串。

let string = """
"<style>* {font-size: 12pt !important;color: #000000 !important;font-family: Montserrat-Regular !important;}</style>Perform the following steps:<br><u>Option 1:</u><br><p>1) Upon receiving a push notification alert, tap on the push notification to launch BIMB Authenticator</p><p>2) Verify the transaction details and choose \"Approve\"</p><p>3) Complete</p><br><u>Option 2:</u><br><ol><p>1) If you didn’t receive push notification, you may launch BIMB Authenticator</p><p>2) Verify the transaction details and choose \"Approve\"</p><p>3) Complete</p>"
"""

label.attributedText = string.attributedStringFromHTML()

© www.soinside.com 2019 - 2024. All rights reserved.