Swift: How to display text with HTML tags using attributed text and adjust its font to system font
If your text contains HTML tags you need to use the attributed text in order to display it in iOS. Otherwise it will be displayed as plain text without HTML formatting.
For example, I have the following text,
Was ist <u>keine</u> Leitlinie von CHECK24?
I need to display it on the iOS device using a UILabel. If I display it without changing the UILabel to a attributed text. It will display as follows,
You can see that the HTML tag <u>
which stands for underline is not being formatted and displayed as a plain text.
In order to solve this issue you need to use attributed text.
let yourText = "Was ist <u>keine</u> Leitlinie von CHECK24?"
let data = Data(yourText.utf8)
if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {yourUILabel.attributedText = attributedString
let font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
yourUILabel.font = font
}
my text is stored in a constant yourText
and I convert it into Data
. Then I use the if
statement declaring the attributedString
and try to convert to HTML format by declaring in the options
[.documentType: NSAttributedString.DocumentType.html]
If the conversion is successful it will be displayed in the UIlabel and the next I set the font size to the system font as I am using the default font size 17.0
let font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
Disclaimer:
The above text I used was from a code challenge which I failed in 2021 April. But I am learning where I failed in order to improve myself and apply again. If you are looking for an iOS Developer, you can consider me for the position in region Berlin, Germany or Hyderabad, India.
This article is only present to help people understand how to convert HTML tags and display them. Its sole purpose is for learning only. As we all are life long learners.
If you like my articles please follow me. You can also support me by https://www.buymeacoffee.com/akarshseggemu