您的位置:首页 > 移动开发

学习WKWebView控件

2015-02-04 16:09 435 查看
如果你曾经在你的App中使用UIWebView加载网页内容的话,你应该体会到了它的诸多不尽人意之处。UIWebView是基于移动版的Safari的,所以它的性能表现十分有限。特别是在对几乎每个Web应用都会使用的JavaScript,表现的尤为糟糕。

但是,所有的这一切都在iOS 8引入了一个新的框架——WebKit,之后变得好起来了。在WebKit框架中,有WKWebView可以替换UIKit的UIWebView和AppKit的WebView,而且提供了在两个平台可以一致使用的接口

直接步入正题

1、和很多控件一样,首先创建对象 这个和UIWebview差不多
web  = [[WKWebView alloc]initWithFrame:self.view.bounds];
web.navigationDelegate = self;

[self.view addSubview:web];
[web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.sina.com"]]];


2、为了美观,在导航条下面价格进度条
progress = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 65, CGRectGetWidth(self.view.frame), 2)];

[self.view addSubview:progress];
[web addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];


3、实现观察者模式中观察webview的加载进度 展示在progressview上

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
NSLog(@"change = %@",change);
if ([keyPath isEqual: @"estimatedProgress"]) {
if (web.estimatedProgress == 1) {
progress.hidden = YES;

}
NSLog(@"--->%f",web.estimatedProgress);
[progress setProgress:web.estimatedProgress animated:YES];
}
}
4、实现wkwebview的代理方法 将会在页面载入完毕后执行。当一个任务完成后,我们使用它来重置progress view的进度。
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
[progress setProgress:0.0 animated:false];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: