87 votes

Afficher le texte html dans uitextview

Comment puis-je afficher du texte HTML en mode texte ?

Par exemple,

string <h1>Krupal testing <span style="font-weight:
bold;">Customer WYWO</span></h1>

Supposons que le texte soit en gras donc il s'affiche en mode texte en tant que chaîne en gras mais je veux afficher du texte normal. Est-ce possible dans le SDK iPhone ?

239voto

BHUPI Points 806

Utilisez le bloc de code suivant pour ios 7+.

NSString *htmlString = @"<h1>Header</h1><h2>Subheader</h2><p>Some <em>text</em></p><img src='http://blogs.babble.com/famecrawler/files/2010/11/mickey_mouse-1097.jpg' width=70 height=100 />";
NSAttributedString *attributedString = [[NSAttributedString alloc]
          initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding]
               options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
    documentAttributes: nil
                 error: nil
];
textView.attributedText = attributedString;

56voto

pableiros Points 4682

Pour Swift 4, Swift 4.2 : et Swift 5

let htmlString = """
    <html>
        <head>
            <style>
                body {
                    background-color : rgb(230, 230, 230);
                    font-family      : 'Arial';
                    text-decoration  : none;
                }
            </style>
        </head>
        <body>
            <h1>A title</h1>
            <p>A paragraph</p>
            <b>bold text</b>
        </body>
    </html>
    """

let htmlData = NSString(string: htmlString).data(using: String.Encoding.unicode.rawValue)

let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html]

let attributedString = try! NSAttributedString(data: htmlData!, options: options, documentAttributes: nil)

textView.attributedText = attributedString

Pour Swift 3 :

let htmlString = """
    <html>
        <head>
            <style>
                body {
                    background-color : rgb(230, 230, 230);
                    font-family      : 'Arial';
                    text-decoration  : none;
                }
            </style>
        </head>
        <body>
            <h1>A title</h1>
            <p>A paragraph</p>
            <b>bold text</b>
        </body>
    </html>
    """

let htmlData = NSString(string: htmlString).data(using: String.Encoding.unicode.rawValue)

let attributedString = try! NSAttributedString(data: htmlData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)

textView.attributedText = attributedString

55voto

KennyTM Points 232647

Utilisez un UIWebView sur iOS 5-.

Sur iOS 6+, vous pouvez utiliser UITextView.attributedString, voir https://stackoverflow.com/a/20996085 pour savoir comment.


Il existe également une méthode -[UITextView setContentToHTMLString:] non documentée. Ne l'utilisez pas si vous souhaitez soumettre à AppStore.

20voto

David Points 1031

La réponse de BHUPI est correcte, mais si vous souhaitez combiner votre police personnalisée de UILabel ou UITextView avec du contenu HTML, vous devez corriger votre html un peu :

NSString *htmlString = @"<b>Bold</b><br><i>Italic</i><p> <del>Deleted</del><p>List<ul><li>Coffee</li><li type='square'>Tea</li></ul><br><a href='URL'>Link </a>";

htmlString = [htmlString stringByAppendingString:@"<style>body{font-family:'YOUR_FONT_HERE'; font-size:'SIZE';}</style>"];
/*Example:

 htmlString = [htmlString stringByAppendingString:[NSString stringWithFormat:@"<style>body{font-family: '%@'; font-size:%fpx;}</style>",_myLabel.font.fontName,_myLabel.font.pointSize]];
*/
 NSAttributedString *attributedString = [[NSAttributedString alloc]
                      initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding]
                           options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                documentAttributes: nil
                             error: nil
            ];
textView.attributedText = attributedString;

Vous pouvez voir la différence sur l'image ci-dessous : enter image description here

12voto

sElanthiraiyan Points 3247

Vous pouvez jeter un oeil aux classes OHAttributedLabel, je les ai utilisées pour surmonter ce genre de problème avec mon textField. En cela, ils ont remplacé la méthode drawRect pour obtenir le style requis.

https://github.com/AliSoftware/OHAttributedLabel

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X