Display Rich Text Using a UIWebView

来源:互联网 发布:刷帖软件 编辑:程序博客网 时间:2024/06/08 19:10

A UITextView is great for displaying multiple lines of simple text. But when you need something more fancy, like headlines or highlighting text, then you should look at UIWebView. It’s not just capable of displaying web pages from a URL, but you can also specify the HTML you want to display as a string.

Create a UIWebView in a controller:

view plaincopy to clipboardprint?
  1. - (void)loadView  
  2. {  
  3.   // Create a custom view hierarchy.  
  4.   CGRect appFrame = [[UIScreen mainScreen] applicationFrame];  
  5.   UIView *view = [[UIView alloc] initWithFrame:appFrame];  
  6.   view.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;  
  7.   self.view = view;  
  8.   [view release];  
  9.   
  10.   CGRect webFrame = [[UIScreen mainScreen] applicationFrame];  
  11.   webView = [[UIWebView alloc] initWithFrame:webFrame];  
  12.   webView.backgroundColor = [UIColor whiteColor];  
  13.   [self.view addSubview:webView];  
  14. }  

Then you can add your rich text to the view like this:

view plaincopy to clipboardprint?
  1. NSString *html = @"<html><head><title>The Meaning of Life</title></head><body><p>...really is <b>42</b>!</p></body></html>";  
  2. [webView loadHTMLString:html baseURL:[NSURL URLWithString:@"http://www.hitchhiker.com/message"]];  

The documentation is not very clear on what the baseURL is used for in the context of HTML that is loaded from a string.