WKWebView 是IOS8新增的 Web瀏覽檢視
WKWebView相對於UIWebView強大了很多,記憶體的消耗相對少了,所提供的介面也豐富了。 title,estimatedProgress是兩個很有用的新API
#import "MYWebViewController.h"
#import <WebKit/WebKit.h>
@interface MYWebViewController ()
//進度條
@property (weak, nonatomic) IBOutlet UIProgressView
*progressView;
@property (nonatomic, weak) WKWebView *webView;
@end
@implementation MYWebViewController
/*
使用步驟
1.匯入WebKit框架
2.匯入WebKit/WebKit.h標頭檔案
*/
- (void)viewDidLoad {
[superviewDidLoad];
//新增WKWebView
WKWebView*webView = [[WKWebViewalloc] initWithFrame:self.view.bounds];
_webView = webView;
[self.viewinsertSubview:webView atIndex:0];
//載入網頁
NSURLRequest*request = [NSURLRequestrequestWithURL:_url];
[webViewloadRequest:request];
//KVO: 讓self物件監聽webView的estimatedProgress
[webView addObserver:selfforKeyPath:@"estimatedProgress"options:NSKeyValueObservingOptionNewcontext:nil];
}
// 只要監聽的屬性有新值就會呼叫
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id>
*)change context:(void *)context
{
_progressView.progress= _webView.estimatedProgress;
_progressView.hidden= _progressView.progress>= 1;
}
// KVO一定要移除觀察者
- (void)dealloc
{
[self.webViewremoveObserver:selfforKeyPath:@"estimatedProgress"];
}
@end
複製程式碼