Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display html text in UITableView

I need to display html strings in UITableViewCells. I used this way:

NSString *htmlString = @"<h1>Header</h1><h2>Subheader</h2><p>Some <em>text</em></p>";
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
textView.attributedText = attributedString;

But it's very slow. Does anyone have another idea?

I read an article about using this: https://github.com/Cocoanetics/DTCoreText to display html string. But i don't know how to use.

like image 528
thinhvd Avatar asked Jun 09 '26 22:06

thinhvd


2 Answers

Many third party classes are available for that like RTLabel. But internally all third-party classes are either converting HTML to attributed string or loading HTML into UIWebView. BOTH WAY WILL WORK SLOWER IN TABLEVIEW CELLS

If you are using HTML text in tableview cells then most convenient way is to make another array for just attributed string. Dont convert HTML to attributed string in cellForRowAtIndexPath. When you are reloading table, make another saperate array just for attributed string by converting all HTML at once.

Load attributed string from your new array. It will load for first time, then it will work smoothly. You can handle one time loading by showing loader.

Hope this will help you...

like image 97
Nirav Gadhiya Avatar answered Jun 12 '26 13:06

Nirav Gadhiya


You shouldn't be performing any heavy lifting inside your cellForRow method.

Instead, you should create each of your attributed strings, store them in an array, and use them when you need to in cellForRow.

textView.attributedText = self.myArrayOfStrings[indexPath.row];

cellForRow should only be reserved for setting properties, and possibly setting up the appearance of your cells. Never do any heavy calculations or animations.

like image 27
Beau Nouvelle Avatar answered Jun 12 '26 12:06

Beau Nouvelle