Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextView Rich text?

Tags:

I was wondering if UITextView can display rich text? I want to have simple formatting on my read only text (like different alignment for different parts of the text). if not, what view should I use?

like image 940
Ali Shafai Avatar asked Sep 17 '09 05:09

Ali Shafai


2 Answers

Generally, the best way to do this is to use a UIWebView and load local content in where you can insert tags and whatever else you need. Local loading should be fast and you can stylize it to look like any uitextview

Another option is to use a UILabel subclass instead and get the Three20 open-souce code. You want the TTStyledTextLabel.

like image 177
coneybeare Avatar answered Oct 11 '22 13:10

coneybeare


Here is a code snippet for anyone trying to do this - use the uiwebview to handle styled text - getting your local js files to work can be trick. Just go into Build Phases -> Compile Sources -> and add the js files you want to access locally in your html content. You can also evaluate strings as javascript from objective c on your webview.

NSString *someHtmlContent = [NSString stringWithFormat:@"<html><head><style type=\"text/css\">body {padding: 0px; margin: 0px; }</style><script src=\"yourLocalJsFile.js\"></script></head><body></body></html>", dynamicText]; 

NSLog(@"HTML with code: \n%@", someHtmlContent);

NSString *resourcePath = [[[[NSBundle mainBundle] resourcePath]
                               stringByReplacingOccurrencesOfString:@"/" withString:@"//"]
                              stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

[MyWebView loadHTMLString:someHtmlContent baseURL:[NSURL URLWithString:
                                            [NSString stringWithFormat:@"file:/%@//", resourcePath]]];

[self.MyWebView setDelegate:self];

Setting the delegate let's you decide how to handle links - do you want them to open in mobile safari or in your webview

like image 43
HarrisonJackson Avatar answered Oct 11 '22 14:10

HarrisonJackson