UIWebView是内置的浏览器控件,可以用它来浏览网页、打开文档,关于浏览网页榜样可以参考UC,手机必备浏览器,至于文档浏览的手机很多图书阅读软件,UIWebView是一个混合体,具体的功能控件内置的,实现一些基本的功能。UIWebView可以查看Html网页,pdf文件,docx文件,txt文件文件,系统自带的Safari就是UIWebView实现的。
页面布局很简单就是一个文本框,一个按钮,一个UIWebView,页面布局如下:

如果想简单一点的话,其实用UIWebView也行,不过需要先准备一些文本数据,具体如下:

①直接拼接Html,用UIWebView显示,viewDidLoad中添加代码:
//直接加载Html字符串
NSString *htmlStr=@"<html><head><title>Html加载</title></head><body>HtmlDemo-FlyElephant</body></html>";
[self.webView loadHTMLString:htmlStr baseURL:nil];

②加载本地的Html网页,Book.html中代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>书籍</title> </head> <body> 少年维特之烦恼-歌德 </body> </html>
viewDidLoad代码:
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Book" ofType:@"html"];
NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[self.webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]];

③加载本地的pdf文件,viewDidLoad代码:
NSURL *url = [[NSBundle mainBundle]URLForResource:@"Book.pdf" withExtension:nil];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];

加载pdf的第二种方式:
NSString *path = [[NSBundle mainBundle]pathForResource:@"Book.pdf" ofType:nil];
//以二进制的形式加载数据
NSData *data = [NSData dataWithContentsOfFile:path];
[self.webView loadData:data MIMEType:@"application/pdf" textEncodingName:@"UTF-8" baseURL:nil];
④加载本地txt文件,viewDidLoad代码如下:
//加载txt
NSURL *url = [[NSBundle mainBundle]URLForResource:@"Book.txt" withExtension:nil];
//设置Url
[self.webView loadRequest:[NSURLRequest requestWithURL:url]];

⑤加载Word,viewDidLoad代码如下:
//加载Word
NSURL *url = [[NSBundle mainBundle]URLForResource:@"Book.docx" withExtension:nil];
//设置加载Url
[self.webView loadRequest:[NSURLRequest requestWithURL:url]];

⑥加载网络数据,跳转按钮事件中实现如下:
NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlText.text]];
[self.webView loadRequest:request];

⑦设置委托,在不同的阶段处理数据,实现UIWebViewDelegate,设置自己本身为委托对象;
[self.webView setDelegate:self];
常用的三个方法:
//加载开始
- (void)webViewDidStartLoad:(UIWebView *)webView{
NSLog(@"加载开始的时候的方法调用");
}
//加载完成
-(void)webViewDidFinishLoad:(UIWebView *)webView{
NSLog(@"加载完成的时候电脑方法调用");
}
//加载出错
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
NSLog(@"加载出错的时候的调用");
}
原文:http://www.cnblogs.com/xiaofeixiang/p/4307573.html