我从 API
响应中获取 HTML
格式的字符串,因此我需要将其设置为标签,同时维护自定义字体(如我的应用程序)并应用样式(粗体、常规等)到标签。
我使用了一个扩展,可以将 HTML
字符串转换为带有换行符等的常规字符串。但是,我可以在此处设置字体,但只能设置一种字体,并且仅以常规字体显示,所以整个标签采用一种字体,我想要的是将粗体 HTML
部分设置为粗体,将常规字体设置为常规 HTML
部分/标签。
extension String {
var htmlToAttributedString: NSAttributedString {
guard let data = data(using: .utf8) else { return NSAttributedString() }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
var htmlToString: String {
return htmlToAttributedString.string
}
}
//set converted html to string here
let whyAttendAttributedText: NSMutableAttributedString = NSMutableAttributedString(attributedString: attendData.whyAttendData?.desc?.htmlToAttributedString ?? NSAttributedString())
//set font here
whyAttendAttributedText.addAttributes([NSMutableAttributedString.Key.font: CommonSettings.shared.getFont(type: .regular, size: descriptionLabel.font.pointSize), NSMutableAttributedString.Key.foregroundColor: UIColor.white], range: NSMakeRange(0, whyAttendAttributedText.length))
我想为文本设置粗体和常规字体,但由于我只设置了一种字体,所以无法获得结果,有没有办法像 HTML
中那样设置粗体和常规字体> 字符串?
最佳答案
这应该有帮助:
extension String {
func attributedString(withRegularFont regularFont: UIFont, andBoldFont boldFont: UIFont) -> NSMutableAttributedString {
var attributedString = NSMutableAttributedString()
guard let data = self.data(using: .utf8) else { return NSMutableAttributedString() }
do {
attributedString = try NSMutableAttributedString(data: data,
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding:String.Encoding.utf8.rawValue],
documentAttributes: nil)
let range = NSRange(location: 0, length: attributedString.length)
attributedString.enumerateAttribute(NSAttributedString.Key.font, in: range, options: .longestEffectiveRangeNotRequired) { value, range, _ in
let currentFont: UIFont = value as! UIFont
var replacementFont: UIFont? = nil
if currentFont.fontName.contains("bold") || currentFont.fontName.contains("Bold") {
replacementFont = boldFont
} else {
replacementFont = regularFont
}
let replacementAttribute = [NSAttributedString.Key.font:replacementFont!]
attributedString.addAttributes(replacementAttribute, range: range)
}
} catch let e {
print(e.localizedDescription)
}
return attributedString
}
}
关于ios - 如何在 swift 4 中将 html 字符串设置为标签时设置常规字体和粗体字体的自定义字体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56214681/