Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to show HTML text on UILabel?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.32k
    Comment on it

    To show HTML text on UILabel we need to convert the text to NSAttributedString. To achieve this we can use following code:

            if let htmlData = htmlString.data(using: String.Encoding.utf16, allowLossyConversion: false) {
                if let attributedString = try? NSMutableAttributedString(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) {
                    label.attributedText = attributedString
                }
            }
    

     

    We can also make an extension on String class like so:

    extension String {
        func attributedString() -> NSAttributedString? {
            if let htmlData = self.data(using: String.Encoding.utf16, allowLossyConversion: false) {
                if let attributedString = try? NSMutableAttributedString(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) {
                    return attributedString
                }
            }
            return nil
        }
    }

     

    In Objective-C following method can be used:

    - (NSAttributedString *)attributedStringFromHtml:(NSString *)htmlString {
        NSData *data = [htmlString dataUsingEncoding:NSUTF16StringEncoding allowLossyConversion:false];
        NSError *err;
        NSAttributedString *attr = [[NSAttributedString alloc] initWithData:data options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:&err];
        if (err) {
            NSLog(@"Error while converting: %@",err.localizedDescription);
        }
        return attr;
    }
    

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: