我有这个 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 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()