iOS开发:webview动态添加配置返回、关闭按钮(简单又完美

2020-10-19  本文已影响0人  阳光的噗哈哈

之前的想法是通过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来动态配置的

上一篇下一篇

猜你喜欢

热点阅读