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

Num*_*r45 5 ios swift

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

问题:我应该创建一个协议并使一切都确认它,即:

protocol CustomDelegate: UINavigationControllerDelegate {
   func didTapCloseButton()
}

public class ViewController: CustomDelegate {
   func didTapCloseButton() {
     //not sure what goes in here?
   }
}
Run Code Online (Sandbox Code Playgroud)

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

感谢您的帮助!

gri*_*ian 5

这是一个简单的解决方案。创建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
    }
}
Run Code Online (Sandbox Code Playgroud)