gpt4 book ai didi

HTML 格式无法快速与 UILabel 一起使用

转载 作者:行者123 更新时间:2023-11-28 07:27:14 25 4
gpt4 key购买 nike

我已经使用这段代码来格式化 UILabel 上的 HTML 内容

 var htmlToAttributedString: NSAttributedString? {
do {
guard let data = 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
}
}

我的 HTML 内容如:

("<p>My Name is <b>Ayush</b> <I>Bansal</I></p>")

当我使用上面的代码进行格式化时,我得到类似(我的名字是 Ayush Bansal)的输出。但我希望我的输出是这样的(我的名字是Ayush Bansal)

最佳答案

你可以使用这个扩展

extension String {
func convertToAttributed(_ defaultFont: UIFont, textColor: UIColor ) -> NSAttributedString? {
guard let data = "".replacingOccurrences(of: "\n", with: "<br>").data(using: .utf8, allowLossyConversion: false) else { return nil }
guard let attributedString = try? NSMutableAttributedString(data: data,
options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
documentAttributes: nil)
else { return nil }

attributedString.enumerateAttribute(NSAttributedString.Key.font,
in: NSRange(location: 0, length: attributedString.length),
options: NSAttributedString.EnumerationOptions(rawValue: 0))
{ (value, range, _) -> Void in
if let oldFont = value as? UIFont {
var newFont = defaultFont
let isBold = oldFont.fontName.lowercased().contains("bold")
let isItalic = oldFont.fontName.lowercased().contains("italic")
if isBold && isItalic {
newFont = UIFont.bolditalicFont(ofSize: 14)
} else if isBold {
newFont = UIFont.boldFont(ofSize: 14)
} else if isItalic {
newFont = UIFont.italicFont(ofSize: 14)
}
attributedString.removeAttribute(NSAttributedString.Key.font, range: range)
attributedString.addAttribute(NSAttributedString.Key.font, value: newFont, range: range)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: textColor, range: range)
}
}
}
}

用法:

yourLabel.attributedText = string.convertToAttributed(font, textColor: textcolor)

关于HTML 格式无法快速与 UILabel 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56184513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com