標籤:
UIWebView是內建的瀏覽器控制項,可以用它來瀏覽網頁、開啟文檔,關於瀏覽網頁榜樣可以參考UC,手機必備瀏覽器,至於文檔瀏覽的手機很多圖書閱讀軟體,UIWebView是一個混合體,具體的功能控制項內建的,實現一些基本的功能。UIWebView可以查看Html網頁,pdf檔案,docx檔案,txt檔案檔案,系統內建的Safari就是UIWebView實現的。
基礎布局
頁面配置很簡單就是一個文字框,一個按鈕,一個UIWebView,頁面配置如下:
如果想簡單一點的話,其實用UIWebView也行,不過需要先準備一些文本資料,具體如下:
資料載入
①直接拼接Html,用UIWebView顯示,viewDidLoad中添加代碼:
//直接載入Html字串 NSString *[email protected]"<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(@"載入出錯的時候的調用");}
iOS開發-UIWebView載入本地和網路資料