Display Rich Text Using a UIWebView

本文介绍如何利用UIWebView在iOS应用中展示包含标题、加粗等格式的富文本内容。通过创建并配置UIWebView,可以加载自定义的HTML字符串来实现复杂的文本样式。

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:

  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:

  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.


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值