最近寫項目的時候,有一個需求桑寨,要加載HTML頁面,并且顯示HTML頁面的title忿檩,查找了相關(guān)文章尉尾,找到了一份非常合適的文章,想看原文請點擊這里燥透。
WKWebView 的estimatedProgress和title 都是KVO模式沙咏,所以可以添加監(jiān)聽:
[webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
[webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
監(jiān)聽的實現(xiàn)方法:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"estimatedProgress"]) {
if (object == webView) {
[self.progressView setAlpha:1.0f];
[self.progressView setProgress:self.currentSubView.webView.estimatedProgress animated:YES];
if(self.currentSubView.webView.estimatedProgress >= 1.0f) {
[UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
[self.progressView setAlpha:0.0f];
} completion:^(BOOL finished) {
[self.progressView setProgress:0.0f animated:NO];
}];
}
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
else if ([keyPath isEqualToString:@"title"])
{
if (object == self.webView) {
self.title = self.webView.title;
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
進(jìn)度條增加了動畫,類似safari的進(jìn)度效果
注意銷毀時一定要移除監(jiān)聽
[webView removeObserver:self forKeyPath:@"estimatedProgress"];
[webView removeObserver:self forKeyPath:@"title"];