为每个在UINavigationController堆栈中的视图控制器创建关闭按钮

5
我希望在导航栏中的每个视图控制器上都有一个关闭按钮。我读到这里,需要创建一个对象作为uinavigationdelegate,我认为此对象将具有类似didTapCloseButton的方法。
问题: 我应该创建一个协议并使所有内容都符合它吗,例如:
protocol CustomDelegate: UINavigationControllerDelegate {
   func didTapCloseButton()
}

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

如何在每个视图的导航栏上显示关闭按钮?当用户点击关闭按钮时,如何使该堆栈上的每个视图都被取消?

感谢您的帮助!


我相信你可能会感到困惑,实际上苹果公司已经实现了UINavigationControllerDelegate1协议。 - ff10
好的,让我编辑我的帖子,以便创建一个从UINavigationDelegate继承的自定义委托。 - Number45
2个回答

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
    }
}

0

不确定这是否是您想要的,但您可以这样做:

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()
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接