Reputation: 1549
How can I display HTML text in textview?
For example,
string <h1>Krupal testing <span style="font-weight:
bold;">Customer WYWO</span></h1>
Suppose text is bold so it display in textview as bold string but I want display normal text. Is this possible in the iPhone SDK?
Upvotes: 89
Views: 138957
Reputation: 16032
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
Upvotes: 58
Reputation: 1071
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:
Upvotes: 20
Reputation: 4808
For some cases UIWebView is a good solution. Because:
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)
}
Upvotes: 1
Reputation: 61
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
Upvotes: 3
Reputation: 20609
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.
Upvotes: 9
Reputation: 6593
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;
Upvotes: 240
Reputation: 523284
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.
Upvotes: 55
Reputation: 990
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
Upvotes: 4
Reputation: 17892
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..
Upvotes: -3
Reputation: 2499
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.
Upvotes: -2
Reputation: 6268
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
Upvotes: 12