您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 開發入門篇(四):UIWebView 結合 UISearchBar 的簡單用法

編輯:iOS 相關資訊

UIWebView 是 iOS 開發中非常常用的一個控件,可以用來瀏覽網頁、打開文檔。本文把 UIWebView 與 UISearchBar 結合起來,做一個最簡陋的「瀏覽器」,順帶熟悉兩者的代理方法。

一、聲明控件與代理

@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];
}

這裡要提醒一句:通過遍歷 subviews 去改 UISearchBar 內部按鈕的文案,屬於依賴私有視圖層級的 hack。系統一升級就可能失效,甚至造成界面異常。正式項目中更合適的做法是把 searchBar 的 showsCancelButton 保持默認,或者在 Keyboard 相關的 returnKeyType 上做文章。

三、實現 UISearchBar 的代理方法

#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:searchBar.text];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}

四、UIWebView 的其他加載方式

除了 loadRequest,UIWebView 還支持幾種常見的加載途徑:

加載本地文件

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]];

注意 baseURL 要指向 HTML 文件所在路徑,這樣頁面中引用的相對路徑資源(CSS、圖片)才能正確載入。傳 nil 的話這些資源全部會丟失。

五、實現加載失敗的回調

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    // 取消類錯誤(-999)在頁面跳轉時很常見,可以忽略
    if (error.code == NSURLErrorCancelled) return;

    UIAlertView *alterview = [[UIAlertView alloc] initWithTitle:@"訪問出錯"
        message:[error localizedDescription] delegate:nil
        cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alterview show];
}

六、其他常用代理方法

// 開始加載
- (void)webViewDidStartLoad:(UIWebView *)webView;

// 加載完成
- (void)webViewDidFinishLoad:(UIWebView *)webView;

// 準備加載,返回 NO 可以攔截該次請求
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
        navigationType:(UIWebViewNavigationType)navigationType;

三個方法的觸發順序是:shouldStartLoad → didStartLoad → didFinishLoad。做進度條時通常在 didStartLoad 顯示、didFinishLoad 隱藏;而 shouldStartLoadWithRequest 因為可以返回 NO 進行攔截,常被用來實現自定義 scheme 的離線資源路由或登錄態校驗。

七、幾點實踐建議

  • ATS 限制。iOS 9 之後默認禁止 HTTP 明文請求。若目標站點不支持 HTTPS,需要在 Info.plist 中配置 NSAppTransportSecurity 例外,否則 loadRequest 會靜默失敗。

  • 新項目請用 WKWebView。UIWebView 在 iOS 12 中已被標記為廢棄,蘋果也不再接受包含它的新提交。WKWebView 具備獨立渲染進程(不阻塞主線程)、原生支持進度 KVO、以及更接近 Safari 的性能表現,遷移成本並不高。

  • UIAlertView 替換。示例中的 UIAlertView 應改為 UIAlertController。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved