之前的想法是通过webview的navigationDelegate的各个生命周期中,判断webview的canGoBack属性,但是有不少缺陷:
比如单页应用的跳转不会触发生命周期,如果在didFinishNavigation中判断canGoBack,这要等页面加载完成才会执行,有很大的延迟.
下面是解决方案,其实很简单,就是通过kvo来监听canGoBack的变化:
[_webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
...
//WkWebView的 回调
-(void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)objectchange:(NSDictionary*)change context:(void*)context{
if([keyPath isEqualToString:@"canGoBack"]) {
[self configLeftItem];
}
}
- (void)configLeftItem {
if ([self.webView canGoBack]) {
UIBarButtonItem *backItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_common_back"] style:UIBarButtonItemStylePlain target:self action:@selector(pop)];
UIBarButtonItem *closeItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_common_blackClose"] style:UIBarButtonItemStylePlain target:self action:@selector(close)];
self.navigationItem.leftBarButtonItem=nil;
self.navigationItem.leftBarButtonItems=@[backItem,closeItem];
}else {
self.navigationItem.leftBarButtonItems=nil;
UIBarButtonItem *backItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_common_back"] style:UIBarButtonItemStylePlain target:self action:@selector(pop)];
self.navigationItem.leftBarButtonItem=backItem;
}
}
-(void)pop{
if([self.webView canGoBack]) {
[self.webView goBack];
}else {
[self.navigationController popViewControllerAnimated:YES];
}
}
-(void)close{
[self.navigationController popViewControllerAnimated:YES];
}
- (void)dealloc {
if(self.viewLoaded)
{
[self.webView removeObserver:self forKeyPath:@"canGoBack"];
}
}
根据微信的体验,微信的底部前进后退的状态判断也是根据监听canGoBack canGoForward来动态配置的
网友评论