Search code examples
iosobjective-cnsattributedstring

NSAttributedString not working for UILabel after using HTML code


I have UILabel and I am assigning html text as below.

m014.text = [NSString stringWithFormat:@"<html><head><style type='text/css'>body {background-color: transparent;border: 0px;margin: 0px;padding: 0px;font-family: '%@'; font-size: %fpx;;ccolor:;}</style></head><body dir='%@'>%@<style type='text/css'> iframe { width: 100%% !important; } img {width: 100%% !important; height: auto;} table {width: 100%%;}</style></body></html>", localize(@"myFontName"), @16, localize(@"myDir"), m014.text];

m014.attributedText = [[NSAttributedString alloc] initWithData: [m014.text dataUsingEncoding:NSUTF32StringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes: nil error: nil];

In iOS 10 & below I can see normal text (plain text) however in iOS 11 & above I see html text in the app. I see html code as it is...

Any idea why this is happening?


Majorly, I feel problem is in below line.

[m014.text dataUsingEncoding:NSUTF32StringEncoding]

But I remember, I used NSUTF32StringEncoding because I was seeing encoded characters.


Solution

  • Thanks to @rmaddy for an answer in comment.

    Update code I used is as below.

    m014.attributedText = [[NSMutableAttributedString alloc] initWithHTML:
        [m014.text dataUsingEncoding:NSUTF8StringEncoding] 
        options: @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, 
        NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} 
        documentAttributes:nil];