我已经使用此代码在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)