为 uinavigationcontroller 堆栈上的每个视图控制器创建关闭按钮



我想在导航堆栈中显示的每个视图控制器上都有一个关闭按钮。我在这里读到我需要创建一个 uinavigationdelegate 的对象,我认为这个对象会有一个像 didTapCloseButton 这样的方法?

问题:我是否应该创建一个协议并使所有内容都得到确认,即:

protocol CustomDelegate: UINavigationControllerDelegate {
   func didTapCloseButton()
}
public class ViewController: CustomDelegate {
   func didTapCloseButton() {
     //not sure what goes in here?
   }
}

如何让关闭按钮显示在每个视图的导航栏上?当用户单击关闭按钮时,如何让它关闭该堆栈上的每个视图?

感谢您的帮助!

这里有一个简单的解决方案。创建 UINavigationController 子类并覆盖 pushViewController 方法。

class NavigationController: UINavigationController {
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        super.pushViewController(viewController, animated: animated)
        let closeBarButtonItem = UIBarButtonItem(
            title: "Close",
            style: .done,
            target: self,
            action: #selector(self.popViewController(animated:)))
        viewController.navigationItem.rightBarButtonItem = closeBarButtonItem
    }
}

不确定这是否是你的意图,但你可以这样做:

protocol CustomDelegate: UINavigationControllerDelegate {
    func didTapCloseButton()
}
extension CustomDelegate where Self : UIViewController{
    func didTapCloseButton(){
        // write your default implementation for all classes
    }
}

现在,对于您拥有的每个UIViewController类,您只需执行以下操作:

class someViewController: CustomDelegate{
    @IBAction buttonClicked (sender: UIButton){
    didTapCloseButton()
    }
}

最新更新