【发布时间】:2019-10-06 10:54:41
【问题描述】:
我从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字符串一样设置粗体和常规字体?
【问题讨论】:
标签: ios objective-c swift uilabel swift4