Display HTML text in UILabel iphone
Asked Answered
M

11

45

I am getting a HTML Response from a webservice Below is the HTML I am getting in response

<p><strong>Topic</strong>Gud mrng.</p>
\n<p><strong>Hello Everybody</strong>: How are you.</p>
\n<p><strong>I am fine</strong>: 1 what about you.</p>

I need to display the text in UILabel.

Please help

Moina answered 8/4, 2013 at 6:1 Comment(1)
use a scroll disabled textView ;)Sourwood
G
15

Use RTLabel library to convert the HTML text. I have used it several times. It works. Here is link to the library and a sample code.

https://github.com/honcheng/RTLabel.

Hope I helped.

Gemeinschaft answered 8/4, 2013 at 8:21 Comment(1)
one issue that i am facing is, after loading text in UITableViewCell when i rotate the device, label text become wider. Same happens for landscape to portrait also. Label text becomes narrow. Why? Any workaround?Browning
D
102

You can do it without any third-party libraries by using attributed text. I believe it does accept HTML fragments, like the one you're getting, but you may want to wrap it in a complete HTML document so that you can specify CSS:

static NSString *html =
    @"<html>"
     "  <head>"
     "    <style type='text/css'>"
     "      body { font: 16pt 'Gill Sans'; color: #1a004b; }"
     "      i { color: #822; }"
     "    </style>"
     "  </head>"
     "  <body>Here is some <i>formatting!</i></body>"
     "</html>";

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 200)];
NSError *err = nil;
label.attributedText =
    [[NSAttributedString alloc]
              initWithData: [html dataUsingEncoding:NSUTF8StringEncoding]
                   options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
        documentAttributes: nil
                     error: &err];
if(err)
    NSLog(@"Unable to parse label text: %@", err);

Not concise, but you can mop up the mess by adding a category to UILabel:

@implementation UILabel (Html)

- (void) setHtml: (NSString*) html
    {
    NSError *err = nil;
    self.attributedText =
        [[NSAttributedString alloc]
                  initWithData: [html dataUsingEncoding:NSUTF8StringEncoding]
                       options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
            documentAttributes: nil
                         error: &err];
    if(err)
        NSLog(@"Unable to parse label text: %@", err);
    }

@end

[someLabel setHtml:@"Be <b>bold!</b>"];
Dimension answered 25/1, 2014 at 20:45 Comment(7)
This method doesn't recognize <br> tag. It simply removes elements ahead of <br> tagKnock
in order for <br> to work you need to set the numberOfLines property for the UILabel to 0: self.titleLbl.numberOfLines = 0;Flatfooted
Can you still set font and color when doing this? self.attributedText = [[NSAttributedString alloc] initWithData: [html dataUsingEncoding:NSUTF8StringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue" size:12.0], NSForegroundColorAttributeName: [UIColor redColor] } documentAttributes: nil error: &err]; Doesn't seem to workStuffing
@DemandedCross I know your comment is ancient but for others, i think you'd need to use the HTML colour code not UIColorGround
sometText<font color=\"#dc2d4e\">372</font> doesn't seem work.Gaspard
[html dataUsingEncoding:NSUTF16StringEncoding] is preferred when working with CJK characters, because NSString is UTF16 encoded, i.e. NSUnicodeStringEncodingDeirdra
Good point, it’s possible that UTF16 might actually be faster in all cases. Then again, if you’re working with a string large enough for that performance problem to be even slightly noticeable, you’re probably not putting that text in a UILabel!Dimension
R
17

Swift 4: version

extension String {
    func htmlAttributedString() -> NSAttributedString? {
        guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
        guard let html = try? NSMutableAttributedString(
            data: data,
            options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
            documentAttributes: nil) else { return nil }
        return html
    }
}

Swift 3: version

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

Swift 2: version

extension String {
        func htmlAttributedString() -> NSAttributedString? {
            guard let data = self.dataUsingEncoding(NSUTF16StringEncoding, allowLossyConversion: false) else { return nil }
            guard let html = try? NSMutableAttributedString(
              data: data, 
              options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], 
              documentAttributes: nil) else { return nil }
            return html
        }
}

use it as:

label.attributedText = yourStringVar.htmlAttributedString()
Reverent answered 8/9, 2016 at 21:46 Comment(1)
My string is: "<b>Pro</b>cess Specialist". Bt its return same what I send to your extension.Supplemental
G
15

Use RTLabel library to convert the HTML text. I have used it several times. It works. Here is link to the library and a sample code.

https://github.com/honcheng/RTLabel.

Hope I helped.

Gemeinschaft answered 8/4, 2013 at 8:21 Comment(1)
one issue that i am facing is, after loading text in UITableViewCell when i rotate the device, label text become wider. Same happens for landscape to portrait also. Label text becomes narrow. Why? Any workaround?Browning
H
6

Swift 4

I would rather suggest to extend NSAttributedString with failable convenience init. String is not responsible for making NSAttributedString by it's nature.

extension NSAttributedString {
     convenience init?(html: String) {
        guard let data = html.data(using: String.Encoding.unicode, allowLossyConversion: false) else {
            return nil
        }
        guard let attributedString = try? NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) else {
            return nil
        }
        self.init(attributedString: attributedString)
    }
}
label.attributedText = NSAttributedString(html: "<span> Some <b>bold</b> and <a href='#/userProfile/uname'> Hyperlink </a> and so on </span>")
Hooten answered 12/3, 2018 at 17:9 Comment(0)
D
3

From: https://mcmap.net/q/373938/-html-string-set-into-uilabel


To convert HTML to plain text Download File

and use

stringByConvertingHTMLToPlainText function on your NSString


OR

You can use DTCoreText (previously known as NSAttributedString Additions for HTML).

Duly answered 8/4, 2013 at 6:23 Comment(2)
DTCoreText build showing compile time error. 'DTHTMLParser.h' file not found. Any idea?Browning
DTCoreText is not previously known as NSAttributedStringMcdavid
B
2

Here is the swift 2 version:

    let htmlStringData = NSString(string: "<strong>Your HTML String here</strong>").dataUsingEncoding(NSUTF8StringEncoding)
    guard let html = htmlStringData else { return }

    do {
        let htmlAttrString = try NSAttributedString(data: html, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
        yourLabel.attributedText = htmlAttrString
    } catch {
        print("An error occured")
    }
Battologize answered 25/7, 2016 at 21:30 Comment(0)
M
1
**// Swift 4 compatible | with setting of colour and font options:**

// add following extension to String:

        func htmlAttributed(family: String?, size: CGFloat, color: UIColor) -> NSAttributedString? {

                let sizeInPx = (size * 0.75)

                do {
                  let htmlCSSString = "<style>" +
                    "html *" +
                    "{" +
                    "font-size: \(sizeInPx)pt !important;" +
                    "color: \(color.hexString ?? "#000000") !important;" +
                    "font-family: \(family ?? "SFUIText-Regular"), SFUIText !important;" +
                  "}</style> \(self)"

                  guard let data = htmlCSSString.data(using: String.Encoding.utf8) else {
                    return nil
                  }

                  return try NSAttributedString(data: data,
                                                options: [.documentType: NSAttributedString.DocumentType.html,
                                                          .characterEncoding: String.Encoding.utf8.rawValue],
                                                documentAttributes: nil)
                } catch {
                  print("error: ", error)
                  return nil
                }
              }

        // add following extension to UIColor:

        extension UIColor{

          var hexString:String? {
            if let components = self.cgColor.components {
              let r = components[0]
              let g = components[1]
              let b = components[2]
              return  String(format: "%02X%02X%02X", (Int)(r * 255), (Int)(g * 255), (Int)(b * 255))
            }
            return nil
          }
        }

    // Sample Use:

    yourLabel.attributedText = locationTitle.htmlAttributed(family: yourLabel.font.fontName,
                                                                           size: yourLabel.font.pointSize,
                                                                           color: yourLabel.textColor)
Metry answered 5/10, 2018 at 8:11 Comment(0)
S
1

The above answer in Swift 3:

    var str = "<html> ... some html ... </html>"

    let htmlStringData = NSString(string: str).data(using: String.Encoding.utf8.rawValue)
    let html = htmlStringData

    do {
        let htmlAttrString = try? NSAttributedString(
                data: html!,
                options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                documentAttributes: nil
        )
        agreementText.attributedText = htmlAttrString
    } catch {
        print("An error occured")
    }
Swaggering answered 13/6, 2019 at 16:0 Comment(0)
K
0

The above answer in Swift 3:

func htmlAttributedString() -> NSAttributedString? {
    guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
    guard let html = try? NSMutableAttributedString(
        data: data,
        options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil) else { return nil }
    return html
}
King answered 5/10, 2016 at 11:47 Comment(0)
H
0

Lately I've been dealing with partial HTML snippets and converting them to attributed strings with the ability to add attributes. Here is my version of the extension

import Foundation
import UIKit

extension String {
  func htmlAttributedString(attributes: [String : Any]? = .none) -> NSAttributedString? {
    guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return .none }
    guard let html = try? NSMutableAttributedString(
      data: data,
      options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
      documentAttributes: .none) else { return .none }


    html.setAttributes(attributes, range: NSRange(0..<html.length))

    return html
  }
}

I call it thus:

let attributes = [
  NSForegroundColorAttributeName: UIColor.lightGray,
  NSFontAttributeName : UIFont.systemFont(ofSize: 12).traits(traits: .traitItalic)
]

label?.attributedText = partialHTMLString.htmlAttributedString(attributes: attributes)
Hakon answered 10/10, 2016 at 10:28 Comment(0)
L
0

Sometimes we need to display HTML content on the screen by using UILabel. How to display the HTML content in UILabel we see that in this article. let’s start and achieve it.

enter image description here

Objective C:

NSString * htmlString = @"<html><body> <b>  HTML in UILabel is here…. </b> </body></html>";
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString
dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute:
NSHTMLTextDocumentType } documentAttributes:nil error:nil];
UILabel * yourLabel = [[UILabel alloc] init];
yourLabel.attributedText = attrStr;

Swift:

var htmlString = “<html><body> <b>  HTML in UILabel is here…. </b> </body></html>”
var attrStr: NSAttributedString? = nil
do {
 if let data = htmlString.data(using: .unicode) {
 attrStr = try? NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
 }
} catch {
}
var yourLabel = UILabel()
yourLabel.attributedText = attrStr

Ref: https://medium.com/@javedmultani16/html-text-in-uilabel-ios-f1e0760bcac5

Lycanthrope answered 23/9, 2019 at 10:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.