UIWebView 是 iOS 開發中相當實用的元件,拿來瀏覽網頁或開啟文件都很方便。本文示範如何把 UISearchBar 與 UIWebView 搭配起來,做出一個外觀簡陋但功能完整的迷你瀏覽器。
首先在標頭檔宣告兩個控件,並讓類別採用 UISearchBarDelegate 與 UIWebViewDelegate 兩個代理協定。
@interface TestView : UIViewController<UISearchBarDelegate,UIWebViewDelegate> @property(nonatomic)UISearchBar* searchBar; @property(nonatomic,retain)UIWebView* webView; @end
//加載searchBar
-(void)initSearchBar {
self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, 40)];
self.searchBar.delegate = self;
self.searchBar.text = @"https://";
//UISearchBar上按鈕的默認文字為Cancel,這裡改為GO(不同版本方法略有差異)
for(id cc in [self.searchBar subviews]) {
for (UIView *view in [cc subviews]) {
if ([NSStringFromClass(view.class) isEqualToString:@"UINavigationButton"]) {
UIButton *btn = (UIButton *)view;
[btn setTitle:@"GO" forState:UIControlStateNormal];
}
}
}
[self.view addSubview:self.searchBar];
}
//加載webview
-(void)initWebView {
self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 60, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-60)];
[self.webView setUserInteractionEnabled:YES]; //設置是否支持交互
[self.webView setDelegate:self]; //接受委托
[self.webView setScalesPageToFit:YES]; //設置自動縮放
[self.view addSubview:self.webView];
}
接著在 viewDidLoad 中呼叫這兩個方法完成載入:
-(void)viewDidLoad {
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor whiteColor]];
[self initSearchBar];
[self initWebView];
}
#pragma mark UISearchBar
//點擊searchbar上的GO時調用
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
[self doSearch:searchBar];
}
//點擊鍵盤上的search時調用
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
[searchBar resignFirstResponder];
[self doSearch:searchBar];
}
//開始執行搜索
- (void)doSearch:(UISearchBar *)searchBar{
[searchBar resignFirstResponder];
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",searchBar.text]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
其中真正讓 webView 載入網頁的,就是建立 NSURLRequest 後呼叫 loadRequest: 這段。除了載入網路網址,UIWebView 也能載入本地檔案或直接吃一段 HTML 字串:
//加載本地文件資源 NSURL *url = [NSURL fileURLWithPath:@"文件路徑"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [webView loadRequest:request]; //讀入一個HTML代碼 NSString *htmlPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"HTML文件地址"]; NSString *htmlString = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:NULL]; [webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:htmlPath]];
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
UIAlertView *alterview = [[UIAlertView alloc] initWithTitle:@"訪問出錯"
message:[error localizedDescription] delegate:nil
cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alterview show];
}
此外還有幾個常用的 UIWebView 代理方法:webViewDidStartLoad:(開始載入時呼叫)、webViewDidFinishLoad:(載入完成時呼叫),以及 shouldStartLoadWithRequest:navigationType:(每次要載入前呼叫,可在其中攔截請求、解析網址)。
補充一句:UIWebView 自 iOS 12 起已被蘋果標記為不建議使用,日後新專案應改用 WKWebView,本文適合作為理解 WebView 代理模型的入門參考。