web-dev-qa-db-fra.com

Afficher le texte HTML dans UILabel iphone

Je reçois une réponse HTML d'un service Web Ci-dessous, le HTML que je reçois en réponse.

<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>

J'ai besoin d'afficher le texte dans UILabel.

S'il vous plaît aider

38
Khushboo

Utilisez la bibliothèque RTLabel pour convertir le texte HTML. Je l'ai utilisé plusieurs fois. Ça marche. Voici un lien vers la bibliothèque et un exemple de code.

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

J'espère que j'ai aidé.

15
Swati

Vous pouvez le faire sans aucune bibliothèque tierce en utilisant un texte attribué. Je crois qu’il accepte les fragments HTML, comme celui que vous obtenez, mais vous voudrez peut-être l’envelopper dans un document HTML complet pour pouvoir spécifier le code 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);

Pas concis, mais vous pouvez nettoyer le désordre en ajoutant une catégorie à 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>"];
92
Paul Cantrell

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
        }
}

utilisez-le comme:

label.attributedText = yourStringVar.htmlAttributedString()
9
Oliver White

Swift 4

Je suggérerais plutôt d’étendre NSAttributedString avec la commodité disponible init. String n'est pas responsable de la création NSAttributedString de par sa 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>")
3
Paul

De: https://stackoverflow.com/a/5581178/237838


Pour convertir le HTML en texte brut Télécharger Fichier

et utilise

stringByConvertingHTMLToPlainText fonction sur votre NSString


OR

Vous pouvez utiliser DTCoreText (précédemment appelé Additions NSAttributedString pour HTML).

3
Chirag Pipaliya

Voici la version de Swift 2:

    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")
    }
2
Beninho85

La réponse ci-dessus dans 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
}
**// 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)
0

Dernièrement, j'ai eu affaire à des extraits de code HTML partiels et je les ai convertis en chaînes avec la possibilité d'ajouter des attributs. Voici ma version de l'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
  }
}

Je l'appelle ainsi:

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

label?.attributedText = partialHTMLString.htmlAttributedString(attributes: attributes)
0
Damo