Skip to content

Instantly share code, notes, and snippets.

@romaonthego
Created September 23, 2013 16:08
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save romaonthego/6672863 to your computer and use it in GitHub Desktop.
Save romaonthego/6672863 to your computer and use it in GitHub Desktop.
UITextView with HTML text (iOS 7)
- (void)viewDidLoad
{
[super viewDidLoad];
UITextView *textView = [[UITextView alloc] init];
textView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:textView];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[textView]-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(textView)]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[textView]-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(textView)]];
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;
}
@NickSuglobov
Copy link

Take into consideration this method is slow. Not good for using in UITableViewCell for example.

@ramkrishna880
Copy link

i used this method working great.can i do this asynchronously like my html has more than 3 images . i want to load asynchronously so that wont block main thread.

@webmd-ios
Copy link

Did you ever find a solution to this? I'm running into the same problem.

I have:

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];

running on a background thread, so the fetch of the images is not blocking the UI. However, the initWithData: does not return until all of the images have been loaded.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment