- Get link
- Other Apps
Today, I came across a very challenging situation which yields into a great learning by end of the day.
Let me give you more details about this to you.
Task: I am getting attributed HTML text which already has multiple tags like bold and line break. I want to show the attributed text in custom font keeping the existing tags.
Problem: When I applied custom font on attributed text, the existing tags like bold and line break overrides.
Solution: I found a style tag which needs to apply on the attributed text.
Let me give you more details about this to you.
Task: I am getting attributed HTML text which already has multiple tags like bold and line break. I want to show the attributed text in custom font keeping the existing tags.
Problem: When I applied custom font on attributed text, the existing tags like bold and line break overrides.
Solution: I found a style tag which needs to apply on the attributed text.
let modifiedFont = String(format: "<span style=\"color:#000000;font-family: '-apple-system', 'SFProText-Regular'; font-size: \(self.font?.pointSize ?? 14.0)\">%@</span>", htmlText)
Code example:
extension UITextView {
func setHTMLFromString(htmlText: String) {
let modifiedFont = String(format: "<span style=\"color:#000000;font-family: '-apple-system', 'SFProText-Regular'; font-size: \(self.font?.pointSize ?? 14.0)\">%@</span>", htmlText)
do {
let attrStr = try NSAttributedString(
data: modifiedFont.data(using: .unicode, allowLossyConversion: true) ?? Data(),
options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
self.attributedText = attrStr
} catch {
self.text = htmlText
}
}
}
thanks for sharing
ReplyDeleteThis comment has been removed by the author.
ReplyDelete