ios UINavigationController返回按钮点击事件的拦截(swift版)

//
//  UIViewController+BackBtnEventIntercept.swift
//  BackBtnEventIntercept_swift
//
//  Created by wangrui on 2017/4/22.
//  Copyright © 2017年 wangrui. All rights reserved.
//

import UIKit

// 如果你想使用的optional方法,你必须用@objc标记您的protocol
public protocol ShouldPopDelegate
{
    //拦截返回按钮的点击事件
    func currentViewControllerShouldPop() -> Bool
}

@objc extension UIViewController: ShouldPopDelegate
{
    public func currentViewControllerShouldPop() -> Bool {
        return true
    }
}

extension UINavigationController: UINavigationBarDelegate
{
    public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool
    {
if self.viewControllers.count < navigationBar.items?.count ?? 1{
            return true
        }
        var shouldPop = true
        // 看一下当前控制器有没有实现代理方法 currentViewControllerShouldPop
        // 如果实现了,根据当前控制器的代理方法的返回值决定
        // 没过没有实现 shouldPop = YES
        let currentVC = self.topViewController
        if (currentVC?.responds(to: #selector(currentViewControllerShouldPop)))! {
            shouldPop = (currentVC?.currentViewControllerShouldPop())!
        }
        
        if (shouldPop == true)
        {
            DispatchQueue.main.async {
                self.popViewController(animated: true)
            }
            
        }
        else
        {
            // 让系统backIndicator 按钮透明度恢复为1
            for subview in navigationBar.subviews
            {
                if (0.0 < subview.alpha && subview.alpha < 1.0) {
                    UIView.animate(withDuration: 0.25, animations: { 
                        subview.alpha = 1.0
                    })
                }
            }
            
        }
        return false
    }
}

  // 如果需要拦截系统返回按钮就重写该方法返回 false
    //返回true就pop,false就不pop
    override func currentViewControllerShouldPop() -> Bool {
        if XXCoreMeyerManager.shareInstance()?.isConnected == true{
            let alertController = UIAlertController(title: "Warning",
                                                    message: "Do you want to disconnect with this camera?", preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "cancel", style: .cancel, handler: nil)
            let okAction = UIAlertAction(title: "sure", style: .default, handler: {
                action in
                self.navigationController?.popViewController(animated: true);
            })
            
            alertController.addAction(cancelAction)
            alertController.addAction(okAction)
            self.present(alertController, animated: true, completion: nil)
            return false;
        }else{
            return true;
        }
       
       
    }

参考博客链接: iOS拦截导航栏返回按钮事件的正确方式

发布了144 篇原创文章 · 获赞 67 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/baidu_40537062/article/details/103741763