如何解决带有下划线的 HTML 文本在 iOS 14 版本中具有带有属性字符串的意外外观
我正在尝试使用 HTML 作为 UILabel 的内容,但在 iOS 14 中遇到一个奇怪的问题,即下划线颜色正在根据文本颜色进行更改。
我正在使用以下代码
-
ViewDidLoad
override func viewDidLoad() { super.viewDidLoad() lblHtml2.htmlText = """ <p><span style="text-decoration:underline">I am facing<span style="color:blue;font-weight:bold"> error </span>in version <span style="color:darkolivegreen;font-weight:bold">of greater than 14 </span> for wrong underline color.</span></p> """ }
我正在使用此扩展程序将 HTML 格式化为属性字符串:
extension UILabel {
var htmlText: String? {
get {
do {
if let attrText = attributedText {
let data = try attrText.data(from: NSRange(location: 0,length: attrText.length),documentAttributes: [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html])
return String(data: data,encoding: .utf8)
}
} catch {
// Fall through
}
return text
}
set {
guard let html = newValue,!html.isEmpty else {
self.text = nil
return
}
do {
let attributedString = try html.htmlToAttributedString(pointSize: font.pointSize,color: textColor,direction: "rtl")
self.attributedText = attributedString
} catch {
self.text = html
}
}
}
}
extension String {
enum Errors: Error {
case AttributedStringConversionError
}
func htmlToAttributedString(pointSize: CGFloat = UIFont.labelFontSize,color: UIColor = .black,direction: String = "ltr") throws -> NSAttributedString {
let fontedHTML = #"""
<html>
<head>
<meta http-equiv="Content-Type" content="text/html"; charset="UTF-8">
<style>
rt {
display: inline
}
body {
font-size: \#(pointSize)px;
font-family: 'system-ui';
color: \#(fontColor(color: color));
}
</style>
</head>
<body>
<div dir="\#(direction)">\#(self)</div>
</body>
</html>
"""#
let data = Data(fontedHTML.utf8)
guard let attrText = try? NSAttributedString(data: data,options: [.documentType: NSAttributedString.DocumentType.html],documentAttributes: nil) else {
throw Errors.AttributedStringConversionError
}
if !attrText.string.isEmpty && attrText.string.hasSuffix("\n") {
return attrText.attributedSubstring(from: NSRange(location: 0,length: attrText.length - 1))
} else {
return attrText
}
}
private func fontColor(color: UIColor) -> String {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
color.getRed(&red,green: &green,blue: &blue,alpha: &alpha)
return "rgba(\(Int(red * 255)),\(Int(green * 255)),\(Int(blue * 255)),\(alpha))"
}
}
在 iOS 13 中正确显示:[预期行为][1] iOS14 中的错误显示:[当前行为][2]
https://i.stack.imgur.com/VK6Co.png [2]:https://i.stack.imgur.com/42Pzz.png
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。