在 uitextview 中显示 html 文本

如何在文本视图中显示 HTML 文本?

比如说,

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

假设文本是粗体的,所以它在 textview 中显示为粗体字符串 但我想显示正常的文本。这可能在 iPhone SDK?

134837 次浏览

Use a UIWebView on iOS 5-.

On iOS 6+ you can use UITextView.attributedString, see https://stackoverflow.com/a/20996085 for how.


There's also an undocumented -[UITextView setContentToHTMLString:] method. Do not use this if you want to submit to AppStore.

You can have a look the OHAttributedLabel classes, I used these to overcome this kind of problem with my textField. In this they have overridden the drawRect method to obtain the required style.

https://github.com/AliSoftware/OHAttributedLabel

My first response was made before iOS 7 introduced explicit support for displaying attributed strings in common controls. You may now set attributedText of UITextView to an NSAttributedString created from HTML content using:

-(id)initWithData:(NSData *)data options:(NSDictionary *)options documentAttributes:(NSDictionary **)dict error:(NSError **)error

- initWithData:options:documentAttributes:error: (Apple Doc)

Original answer, preserved for history:

Unless you use a UIWebView, your solution will rely directly on CoreText. As ElanthiraiyanS points out, some open source projects have emerged to simplify rich text rendering. I would recommend NSAttributedString-Additions-For-HTML (Edit: the project has been supplanted DTCoreText), which features classes to generate and display attributed strings from HTML.

You can also use one more way. Three20 library offers a method through which we can construct a styled textView. You can get the library here: http://github.com/facebook/three20/

The class TTStyledTextLabel has a method called textFromXHTML: I guess this would serve the purpose. But it would be possible in readonly mode. I don't think it will allow to write or edit HTML content.

There is also a question which can help you regarding this: HTML String content for UILabel and TextView

I hope its helpful.

NSDoc save the text file in a string to an html file then simultaneously load it into a webview that is in the same place as your UITextView..

Use following block of code for 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;

Answer has fitted to me that from BHUPI.

The code transfer to swift as below:

Pay attention "allowLossyConversion: false"

if you set the value to true, it will show pure text.

let theString = "<h1>H1 title</h1><b>Logo</b><img src='http://www.aver.com/Images/Shared/logo-color.png'><br>~end~"


let theAttributedString = try! NSAttributedString(data: theString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)


UITextView_Message.attributedText = theAttributedString

BHUPI's answer is correct, but if you would like to combine your custom font from UILabel or UITextView with HTML content, you need to correct your html a bit:

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;

You can see the difference on the picture below: enter image description here

For Swift 4, Swift 4.2: and 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

For 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

For Swift3

    let theString = "<h1>H1 title</h1><b>Logo</b><img src='http://www.aver.com/Images/Shared/logo-color.png'><br>~end~"


let theAttributedString = try! NSAttributedString(data: theString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)


UITextView_Message.attributedText = theAttributedString

For some cases UIWebView is a good solution. Because:

  • it displays tables, images, other files
  • it's fast (comparing with NSAttributedString: NSHTMLTextDocumentType)
  • it's out of the box

Using NSAttributedString can lead to crashes, if html is complex or contains tables (so example)

For loading text to web view you can use the following snippet (just example):

func loadHTMLText(_ text: String?, font: UIFont) {
let fontSize = font.pointSize * UIScreen.screens[0].scale
let html = """
<html><body><span style=\"font-family: \(font.fontName); font-size: \(fontSize)\; color: #112233">\(text ?? "")</span></body></html>
"""
self.loadHTMLString(html, baseURL: nil)
}