Howard
Howard

Reputation: 43

Convert utf-8 text to UILabel

I'm trying to download the text in utf-8 format from the JSON file stored in the server, which then would be used as the text in the UILabel.

Right now, I don't know what code I should include in the text so that the targeted wordings

1) could be bold

2) whose font size could be changed to, say 18, from the default 15 in the UILabel

For Example:

< b>Topic< /b> (no space inside <> in practice, just try to avoid the formatting issue here..). Just like, if I want to open a new line after a sentence, I could do the following:

"This is the first sentence\r\nThis is the second sentence",

it would appear as the below in the UILabel

Output:

This is the first sentence

This is the second sentence

Thanks for the help!

Upvotes: 1

Views: 603

Answers (1)

dahiya_boy
dahiya_boy

Reputation: 9503

The way you are doing is know as Attributed string or you can say formated string.

As you are using HTML entity in the string and you want these HTML entity will reflect according to its tag then you have to do folloeing :

  1. Convert HTML to Atrributed String.
  2. Assign attributed string to label.

Code

  1. Convert Simple string to attributed string.

     extension String{
     func convertHtml() -> NSAttributedString{
        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do{
            return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
        }catch{
            return NSAttributedString()
        }
      }
    }
    
  2. Assign it as attributed text.

    self.lblAtt.attributedText = STRHTML2.convertHtml()
    

Example

Test String : "hello, <b>john</b>"

Output :

enter image description here

Upvotes: 1

Related Questions