iOS_UIWebView、WKWebView使用詳解
轉自:http://www.jianshu.com/p/556c988e2707
github程式碼下載
一、整體介紹
UIWebView
自iOS2就有,WKWebView
從iOS8才有,毫無疑問WKWebView
將逐步取代笨重的UIWebView
。通過簡單的測試即可發現UIWebView
佔用過多記憶體,且記憶體峰值更是誇張。WKWebView
網頁載入速度也有提升,但是並不像記憶體那樣提升那麼多。下面列舉一些其它的優勢:
- 更多的支援HTML5的特性
- 官方宣稱的高達60fps的滾動重新整理率以及內建手勢
- Safari相同的JavaScript引擎
- 將UIWebViewDelegate與UIWebView拆分成了14類與3個協議(
- 另外用的比較多的,增加載入進度屬性:
estimatedProgress
二、UIWebView使用說明
1 舉例:簡單的使用
UIWebView
使用非常簡單,可以分為三步,也是最簡單的用法,顯示網頁
- (void)simpleExampleTest {
// 1.建立webview,並設定大小,"20"為狀態列高度
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20 )];
// 2.建立請求
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]];
// 3.載入網頁
[webView loadRequest:request];
// 最後將webView新增到介面
[self.view addSubview:webView];
}
2 一些實用函式
- 載入函式。
- (void)loadRequest:(NSURLRequest *)request;
- (void )loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL;
UIWebView
不僅可以載入HTML頁面,還支援pdf、word、txt、各種圖片等等的顯示。下面以載入mac桌面上的png圖片:/Users/coohua/Desktop/bigIcon.png
為例
// 1.獲取url
NSURL *url = [NSURL fileURLWithPath:@"/Users/coohua/Desktop/bigIcon.png"];
// 2.建立請求
NSURLRequest *request=[NSURLRequest requestWithURL:url];
// 3.載入請求
[self.webView loadRequest:request];
- 網頁導航重新整理有關函式
// 重新整理
- (void)reload;
// 停止載入
- (void)stopLoading;
// 後退函式
- (void)goBack;
// 前進函式
- (void)goForward;
// 是否可以後退
@property (nonatomic, readonly, getter=canGoBack) BOOL canGoBack;
// 是否可以向前
@property (nonatomic, readonly, getter=canGoForward) BOOL canGoForward;
// 是否正在載入
@property (nonatomic, readonly, getter=isLoading) BOOL loading;
3 代理協議使用:UIWebViewDelegate
一共有四個方法
/// 是否允許載入網頁,也可獲取js要開啟的url,通過擷取此url可與js互動
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *urlString = [[request URL] absoluteString];
urlString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];
NSLog(@"urlString=%@---urlComps=%@",urlString,urlComps);
return YES;
}
/// 開始載入網頁
- (void)webViewDidStartLoad:(UIWebView *)webView {
NSURLRequest *request = webView.request;
NSLog(@"webViewDidStartLoad-url=%@--%@",[request URL],[request HTTPBody]);
}
/// 網頁載入完成
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSURLRequest *request = webView.request;
NSURL *url = [request URL];
if ([url.path isEqualToString:@"/normal.html"]) {
NSLog(@"isEqualToString");
}
NSLog(@"webViewDidFinishLoad-url=%@--%@",[request URL],[request HTTPBody]);
NSLog(@"%@",[self.webView stringByEvaluatingJavaScriptFromString:@"document.title"]);
}
/// 網頁載入錯誤
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
NSURLRequest *request = webView.request;
NSLog(@"didFailLoadWithError-url=%@--%@",[request URL],[request HTTPBody]);
}
4 與js互動
主要有兩方面:js執行OC程式碼、oc調取寫好的js程式碼
- js執行OC程式碼:js是不能執行oc程式碼的,但是可以變相的執行,js可以將要執行的操作封裝到網路請求裡面,然後oc攔截這個請求,獲取url裡面的字串解析即可,這裡用到代理協議的
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
函式。 - oc調取寫好的js程式碼:這裡用到UIwebview的一個方法。示例程式碼一個是網頁定位,一個是獲取網頁title:
// 實現自動定位js程式碼, htmlLocationID為定位的位置(由js開發人員給出),實現自動定位程式碼,應該在網頁載入完成之後再呼叫
NSString *javascriptStr = [NSString stringWithFormat:@"window.location.href = '#%@'",htmlLocationID];
// webview執行程式碼
[self.webView stringByEvaluatingJavaScriptFromString:javascriptStr];
// 獲取網頁的title
NSString *title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"]
- 與js互動的例項
很多時候,我們要對網頁做一些編輯,比如載入一個網頁後,個別原因,我們不想顯示新聞的來源,如下圖的新聞來源“新華網”,網頁的連結如下:http://op.inews.qq.com/mcms/h5/default/detail?id=NEW2016103101306200&refer=100000050
(可能已經失效)
火狐瀏覽器中檢視
那我們就可以使用js程式碼將這個標籤去掉,且只留下時間。js程式碼的編寫,根據火狐瀏覽器檢視它的標籤名稱,然後做處理,如上圖,具體程式碼如下:
- (void)deleteNewsSource {
// 1.去掉頁面標題
NSMutableString *str = [NSMutableString string];
// 去掉導航頁,如果想把“騰訊新聞”導航欄一併去掉,就開啟註釋
// [str appendString:@"document.getElementsByClassName('g-header')[0].style.display = 'none';"];
// 來源
[str appendString:@"if(document.getElementsByClassName('g-wrapper-author')[0].innerHTML.indexOf(' ') == -1){document.getElementsByClassName('g-wrapper-author')[0].innerHTML = document.getElementsByClassName('g-wrapper-author')[0].innerHTML}else{document.getElementsByClassName('g-wrapper-author')[0].innerHTML = document.getElementsByClassName('g-wrapper-author')[0].innerHTML.split(' ')[1];}"];
// 執行js程式碼
[_webView stringByEvaluatingJavaScriptFromString:str];
}
程式碼執行的時機,一般情況下是等待網頁載入完成- (void)webViewDidFinishLoad:(UIWebView *)webView
裡面執行,比較合理,但是有延遲,我們會發現剛開始有來源,然後突然又沒有了,即js程式碼執行有延遲。
這樣的話,我們可以在- (void)webViewDidStartLoad:(UIWebView *)webView
網頁開始載入裡面開啟一個定時器,比如定時0.2秒(根據需要自己設定),在定時器裡面不停的呼叫- (void)deleteNewsSource
方法即可解決。然後在- (void)webViewDidFinishLoad:(UIWebView *)webView
裡面關掉定時器。另外定時器容易引起迴圈引用,一定要注意釋放。比如可以在viewDidDisappear方法裡釋放定時器。。。
- (void)webViewDidStartLoad:(UIWebView *)webView {
// 1.去掉頁面來源標籤,時間根據需要自己設定,定時器在這裡開啟具有一定危險性
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(deleteNewsSource) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
self.timer = timer;
}
三、WKWebView使用說明
1 簡單使用
與UIWebview一樣,僅需三步:
- (void)simpleExampleTest {
// 1.建立webview,並設定大小,"20"為狀態列高度
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];
// 2.建立請求
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]];
// 3.載入網頁
[webView loadRequest:request];
// 最後將webView新增到介面
[self.view addSubview:webView];
}
2 一些實用函式
- 載入網頁函式
相比UIWebview,WKWebView也支援各種檔案格式,並新增了loadFileURL
函式,顧名思義載入本地檔案。
/// 模擬器除錯載入mac本地檔案
- (void)loadLocalFile {
// 1.建立webview,並設定大小,"20"為狀態列高度
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];
// 2.建立url userName:電腦使用者名稱
NSURL *url = [NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"];
// 3.載入檔案
[webView loadFileURL:url allowingReadAccessToURL:url];
// 最後將webView新增到介面
[self.view addSubview:webView];
}
/// 其它三個載入函式
- (WKNavigation *)loadRequest:(NSURLRequest *)request;
- (WKNavigation *)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
- (WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL;
- 網頁導航重新整理相關函式
和UIWebview幾乎一樣,不同的是有返回值,WKNavigation(已更新),另外增加了函式reloadFromOrigin
和goToBackForwardListItem
。- reloadFromOrigin會比較網路資料是否有變化,沒有變化則使用快取,否則從新請求。
- goToBackForwardListItem:比向前向後更強大,可以跳轉到某個指定歷史頁面
@property (nonatomic, readonly) BOOL canGoBack;
@property (nonatomic, readonly) BOOL canGoForward;
- (WKNavigation *)goBack;
- (WKNavigation *)goForward;
- (WKNavigation *)reload;
- (WKNavigation *)reloadFromOrigin; // 增加的函式
- (WKNavigation *)goToBackForwardListItem:(WKBackForwardListItem *)item; // 增加的函式
- (void)stopLoading;
- 一些常用屬性
- allowsBackForwardNavigationGestures:BOOL型別,是否允許左右劃手勢導航,預設不允許
- estimatedProgress:載入進度,取值範圍0~1
- title:頁面title
- .scrollView.scrollEnabled:是否允許上下滾動,預設允許
- backForwardList:WKBackForwardList型別,訪問歷史列表,可以通過前進後退按鈕訪問,或者通過goToBackForwardListItem函式跳到指定頁面
3 代理協議使用
一共有三個代理協議:
- WKNavigationDelegate:最常用,和UIWebViewDelegate功能類似,追蹤載入過程,有是否允許載入、開始載入、載入完成、載入失敗。下面會對函式做簡單的說明,並用數字標出呼叫的先後次序:1-2-3-4-5
三個是否允許載入函式:
/// 接收到伺服器跳轉請求之後呼叫 (伺服器端redirect),不一定呼叫
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation;
/// 3 在收到伺服器的響應頭,根據response相關資訊,決定是否跳轉。decisionHandler必須呼叫,來決定是否跳轉,引數WKNavigationActionPolicyCancel取消跳轉,WKNavigationActionPolicyAllow允許跳轉
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler;
/// 1 在傳送請求之前,決定是否跳轉
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;
追蹤載入過程函式:
/// 2 頁面開始載入
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation;
/// 4 開始獲取到網頁內容時返回
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation;
/// 5 頁面載入完成之後呼叫
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;
/// 頁面載入失敗時呼叫
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation;
- WKScriptMessageHandler:必須實現的函式,是APP與js互動,提供從網頁中收訊息的回撥方法
/// message: 收到的指令碼資訊.
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;
- WKUIDelegate:UI介面相關,原生控制元件支援,三種提示框:輸入、確認、警告。首先將web提示框攔截然後再做處理。
/// 建立一個新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures;
/// 輸入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler;
/// 確認框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;
/// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler;
四、示例程式碼
- 程式碼可以實現一般網路顯示,載入本地檔案(pdf、word、txt、圖片等等)
- 搜尋框搜尋介面,搜尋框輸入
file://
則載入本地檔案,http://
則載入網路內容,如果兩者都不是則搜尋輸入的關鍵字。 - 下部網路導航,後退、前進、重新整理、用Safari開啟連結四個按鈕
/// 控制元件高度
#define kSearchBarH 44
#define kBottomViewH 44
/// 螢幕大小尺寸
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#import "ViewController.h"
#import <WebKit/WebKit.h>
@interface ViewController () <UISearchBarDelegate, WKNavigationDelegate>
@property (nonatomic, strong) UISearchBar *searchBar;
/// 網頁控制導航欄
@property (weak, nonatomic) UIView *bottomView;
@property (nonatomic, strong) WKWebView *wkWebView;
@property (weak, nonatomic) UIButton *backBtn;
@property (weak, nonatomic) UIButton *forwardBtn;
@property (weak, nonatomic) UIButton *reloadBtn;
@property (weak, nonatomic) UIButton *browserBtn;
@property (weak, nonatomic) NSString *baseURLString;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// [self simpleExampleTest];
[self addSubViews];
[self refreshBottomButtonState];
[self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]]];
}
- (void)simpleExampleTest {
// 1.建立webview,並設定大小,"20"為狀態列高度
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];
// 2.建立請求
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]];
// // 3.載入網頁
[webView loadRequest:request];
// [webView loadFileURL:[NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"] allowingReadAccessToURL:[NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"]];
// 最後將webView新增到介面
[self.view addSubview:webView];
}
/// 模擬器載入mac本地檔案
- (void)loadLocalFile {
// 1.建立webview,並設定大小,"20"為狀態列高度
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];
// 2.建立url userName:電腦使用者名稱
NSURL *url = [NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"];
// 3.載入檔案
[webView loadFileURL:url allowingReadAccessToURL:url];
// 最後將webView新增到介面
[self.view addSubview:webView];
}
- (void)addSubViews {
[self addBottomViewButtons];
[self.view addSubview:self.searchBar];
[self.view addSubview:self.wkWebView];
}
- (void)addBottomViewButtons {
// 記錄按鈕個數
int count = 0;
// 新增按鈕
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:@"後退" forState:UIControlStateNormal];
[button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
[button.titleLabel setFont:[UIFont systemFontOfSize:15]];
button.tag = ++count; // 標記按鈕
[button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside];
[self.bottomView addSubview:button];
self.backBtn = button;
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:@"前進" forState:UIControlStateNormal];
[button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
[button.titleLabel setFont:[UIFont systemFontOfSize:15]];
button.tag = ++count;
[button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside];
[self.bottomView addSubview:button];
self.forwardBtn = button;
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:@"重新載入" forState:UIControlStateNormal];
[button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
[button.titleLabel setFont:[UIFont systemFontOfSize:15]];
button.tag = ++count;
[button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside];
[self.bottomView addSubview:button];
self.reloadBtn = button;
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:@"Safari" forState:UIControlStateNormal];
[button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
[button.titleLabel setFont:[UIFont systemFontOfSize:15]];
button.tag = ++count;
[button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside];
[self.bottomView addSubview:button];
self.browserBtn = button;
// 統一設定frame
[self setupBottomViewLayout];
}
- (void)setupBottomViewLayout
{
int count = 4;
CGFloat btnW = 80;
CGFloat btnH = 30;
CGFloat btnY = (self.bottomView.bounds.size.height - btnH) / 2;
// 按鈕間間隙
CGFloat margin = (self.bottomView.bounds.size.width - btnW * count) / count;
CGFloat btnX = margin * 0.5;
self.backBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);
btnX = self.backBtn.frame.origin.x + btnW + margin;
self.forwardBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);
btnX = self.forwardBtn.frame.origin.x + btnW + margin;
self.reloadBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);
btnX = self.reloadBtn.frame.origin.x + btnW + margin;
self.browserBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);
}
/// 重新整理按鈕是否允許點選
- (void)refreshBottomButtonState {
if ([self.wkWebView canGoBack]) {
self.backBtn.enabled = YES;
} else {
self.backBtn.enabled = NO;
}
if ([self.wkWebView canGoForward]) {
self.forwardBtn.enabled = YES;
} else {
self.forwardBtn.enabled = NO;
}
}
/// 按鈕點選事件
- (void)onBottomButtonsClicled:(UIButton *)sender {
switch (sender.tag) {
case 1:
{
[self.wkWebView goBack];
[self refreshBottomButtonState];
}
break;
case 2:
{
[self.wkWebView goForward];
[self refreshBottomButtonState];
}
break;
case 3:
[self.wkWebView reload];
break;
case 4:
[[UIApplication sharedApplication] openURL:self.wkWebView.URL];
break;
default:
break;
}
}
#pragma mark - WKWebView WKNavigationDelegate 相關
/// 是否允許載入網頁 在傳送請求之前,決定是否跳轉
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
NSString *urlString = [[navigationAction.request URL] absoluteString];
urlString = [urlString stringByRemovingPercentEncoding];
// NSLog(@"urlString=%@",urlString);
// 用://擷取字串
NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];
if ([urlComps count]) {
// 獲取協議頭
NSString *protocolHead = [urlComps objectAtIndex:0];
NSLog(@"protocolHead=%@",protocolHead);
}
decisionHandler(WKNavigationActionPolicyAllow);
}
#pragma mark - searchBar代理方法
/// 點選搜尋按鈕
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
// 建立url
NSURL *url = nil;
NSString *urlStr = searchBar.text;
// 如果file://則為開啟bundle本地檔案,http則為網站,否則只是一般搜尋關鍵字
if([urlStr hasPrefix:@"file://"]){
NSRange range = [urlStr rangeOfString:@"file://"];
NSString *fileName = [urlStr substringFromIndex:range.length];
url = [[NSBundle mainBundle] URLForResource:fileName withExtension:nil];
// 如果是模擬器載入電腦上的檔案,則用下面的程式碼
// url = [NSURL fileURLWithPath:fileName];
}else if(urlStr.length>0){
if ([urlStr hasPrefix:@"http://"]) {
url=[NSURL URLWithString:urlStr];
} else {
urlStr=[NSString stringWithFormat:@"http://www.baidu.com/s?wd=%@",urlStr];
}
urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
url=[NSURL URLWithString:urlStr];
}
NSURLRequest *request=[NSURLRequest requestWithURL:url];
// 載入請求頁面
[self.wkWebView loadRequest:request];
}
#pragma mark - 懶載入
- (UIView *)bottomView {
if (_bottomView == nil) {
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kBottomViewH, kScreenWidth, kBottomViewH)];
view.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];
[self.view addSubview:view];
_bottomView = view;
}
return _bottomView;
}
- (UISearchBar *)searchBar {
if (_searchBar == nil) {
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, kSearchBarH)];
searchBar.delegate = self;
searchBar.text = @"http://www.cnblogs.com/mddblog/";
_searchBar = searchBar;
}
return _searchBar;
}
- (WKWebView *)wkWebView {
if (_wkWebView == nil) {
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20 + kSearchBarH, kScreenWidth, kScreenHeight - 20 - kSearchBarH - kBottomViewH)];
webView.navigationDelegate = self;
// webView.scrollView.scrollEnabled = NO;
// webView.backgroundColor = [UIColor colorWithPatternImage:self.image];
// 允許左右劃手勢導航,預設允許
webView.allowsBackForwardNavigationGestures = YES;
_wkWebView = webView;
}
return _wkWebView;
}
@end
相關推薦
iOS_UIWebView、WKWebView使用詳解
轉自:http://www.jianshu.com/p/556c988e2707 github程式碼下載 一、整體介紹 UIWebView自iOS2就有,WKWebView從iOS8才有,毫無疑問WKWebView將逐步取代笨重的UIWebView。通過簡單的測試
css中的px、em、rem 詳解
博客 選擇 原因 www order size arc 字體 處理 概念介紹: 1、px (pixel,像素):是一個虛擬長度單位,是計算機系統的數字化圖像長度單位,如果px要換算成物理長度,需要指定精度DPI(Dots Per Inch,每英寸像素數),在掃描打印時一般
Storm概念、原理詳解及其應用(一)BaseStorm
when 結構 tails 並發數 vm 虛擬機 cif 異步 優勢 name 本文借鑒官文,添加了一些解釋和看法,其中有些理解,寫的比較粗糙,有問題的地方希望大家指出。寫這篇文章,是想把一些官文和資料中基礎、重點拿出來,能總結出便於大家理解的話語。與大多數“wordc
slice()、splice()詳解
log 破壞 light clas logs 數組 刪除 ora 自己 前面在開發的時候對於slice()、splice()這兩個函數老是模糊不清,不清楚具體的參數傳參以及用法。 今天寫個筆記專門記錄一下。 1、slice() 從指定位置刪除數組裏面的元素,可以傳一個或者
Oracle not in查不到應有的結果(NULL、IN、EXISTS詳解)
from 邏輯運算 zha order .net 提升 特點 where zhang 問題:語句1 : Select * from table1 A where A.col1 not in ( select col1 from table2
24、sam- 詳解 https://davetang.org/wiki/tiki-index.php?page=SAM
sco tran lis string轉換 similar in use 位置 rac tro 編輯距離Edit Distance:從字符串a變到字符串b,所需要的最少的操作步驟(插入I,刪除D,更改)為兩個字符串之間的編輯距離。這也是sam文檔中對NM這個tag的定義。編
CGI編程中POST、GET詳解
cgi編程中post、get詳解什麽是 HTTP?超文本傳輸協議(HTTP)的設計目的是保證客戶機與服務器之間的通信。HTTP 的工作方式是客戶機與服務器之間的請求-應答協議。web 瀏覽器可能是客戶端,而計算機上的網絡應用程序也可能作為服務器端。舉例:客戶端(瀏覽器)向服務器提交 HTTP 請求;服務器向客
cookie、json詳解
font eval 全局變量 var 如果 split cookies 有效 cti 什麽是cookie 1.cookie是存儲於訪問者計算機中的變量2.cookie是瀏覽器提供的一種機制3.可以由js控制(設置、讀取、刪除)4.cookie可以實現跨頁面全局變量可以跨越同
[轉載]Linux C 字符串函數 sprintf()、snprintf() 詳解
數組 test 不足 同時 逗號 itoa 表示 成了 nat 一、sprintf() 函數詳解 在將各種類 型的數據構造成字符串時,sprintf 的強大功能很少會讓你失望。 由於 sprintf 跟 printf 在用法上幾乎一樣,只是打印的目的地不同而已,前者打印到字
原碼、反碼、補碼 詳解
blog 應該 符號 order 感覺 最小值 而是 們的 有符號 作者:張子秋出處:http://www.cnblogs.com/zhangziqiu/ 本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法
javascript中call、apply、bind詳解
組裝 div 分析 rgs 特性 類型 bind詳解 中修改 不支持 1.apply和call的區別在哪裏 2.什麽情況下用apply,什麽情況下用call 3.apply的其他巧妙用法(一般在什麽情況下可以使用apply) 我首先從網上查到關於apply和
【我的Linux,我做主】Linux系統文件操作之cp、rm、mv詳解
Linux基礎知識 系統運維 對文本文件的操作非常基礎而且和重要,掌握它們後操作文本你會更加得心應手。要復制文件,請使用cp(copy)這個命令,cp這個命令的用途可多了,除了單純的復制之外,還可以建立建立快捷方式,對比兩個文件的新舊程度從而決定是否更新,以及復制整個目錄下的文件等功能。至於移動目錄和
shell循環:for、while、until——詳解
循環 for while until 循環執行 :將某代碼段重復運行多次; 重復運行多少次: 循環次數事先已知 ;循環次數事先未知 ;有進入條件和退出條件。三種循環體:for、while、until。再循環前前介紹步進,在循環中經常用到步進。步進顯示1-10[root@centos6mini
python讀文件的三個方法read()、readline()、readlines()詳解
pytho class readline col 變量 type 返回 限制 log """ 1、讀取文件的三個方法:read()、readline()、readlines() 2、三個方法均可接受一個變量用以限制每次讀取的數據量,通常不使用該變量。 """
磁盤調度算法FCFS、SSTF、SCAN、CSCAN詳解
磁盤調度算法 Java實現 常見的磁盤調度算法有:1.FCFS:先來先服務算法;2.SSTF:最短尋道時間算法;3.SCAN:掃描算法(也叫電梯調度算法);4.CSCAN:循環掃描算法 算法的詳細介紹:FCFS:算法思想非常簡單,就是不論初始磁頭在什麽位置,都是按照服務隊列的先後順序依次處理進程,可以
2 類、實例、屬性、方法詳解
obj tps 圖片 AD lex 間接 年齡 AS 其它 類的語法 上面的代碼其實有問題,屬性名字和年齡都寫死了,想傳名字傳不進去。 1 class Person(object): 2 def __init__(self, name, age): 3 se
js 中offsetTop、offsetLeft、offsetWidth、offsetHeight詳解
tle setw lse solid 內容 art AI 垂直滾動條 one 1. 偏移量共包括offsetTop、offsetLeft、offsetWidth、offsetHeight 元素:內容大小(width、height)、內邊距(padding)、邊框(borde
html 5 本地數據庫-- Web Sql Database核心方法openDatabase、transaction、executeSql 詳解
web 更新 數據庫 下載地址 最重要的 綠色 -- mysq sele Web SQL數據庫API實際上不是HTML5規範的組成部分,而是單獨的規範。它通過一套API來操縱客戶端的數據庫。Safari、Chrome、Firefox、Opera等主流瀏覽器都已經支持Web
RIP概述、原理詳解及實驗驗證
RIP 路由 RIP路由協議 一.路由類型: 直連路由——設備直連的網絡默認路由靜態路由——管理員手動配置的路由動態路由(IGP)internal gateway protocol1.DV—距離矢量路由協議——RIP IGRP EIGRP2.LS—鏈路狀態路由協議——ISIS OSPF 二.RI
搜索引擎系列五:Lucene索引詳解(IndexWriter詳解、Document詳解、索引更新)
let integer 自己 textfield app tdi AS query rect 一、IndexWriter詳解 問題1:索引創建過程完成什麽事? 分詞、存儲到反向索引中 1. 回顧Lucene架構圖: 介紹我們編寫的應用程序要完成數據的收集,再將數據