如何在所有视图控制器的导航栏中添加一个公共按钮?

How to add a common button in nav bar in all view controllers?

我想 add/remove 导航栏中的按钮作为我应用程序中所有视图控制器中的子视图。我如何将此 add/remove 移动到通用代码,以便我更新现有代码以实现此功能的工作量减少?

我知道我可以在 UIViewController 扩展中添加 add/remove 函数,然后从每个 VC 中调用它,但这需要更新我所有现有的代码.

还有其他更简单的方法吗?

var condition: Bool = false

class MyViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // Add button in navbar
        if condition {
            self.addTopButton()
        } else {
            self.removeTopButton()
        }
    }

    func addTopButton() {
        // create a button programatically and add it as subview in navbar
    }

    func removeTopButton() {
        // remove top button
    }
}

您可以为所有 class 需要的按钮创建父视图控制器。

class ParentViewController: UIViewController {
    var condition: Bool = false

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // Add button in navbar
        if condition {
            self.addTopButton()
        } else {
            self.removeTopButton()
        }
    }

    func addTopButton() {
        // create a button programatically and add it as subview in navbar
    }

    func removeTopButton() {
        // remove top button
    }
}

其他classes可以继承,也可以覆盖方法

class MyViewController: ParentViewController {
    override func addTopButton() {
        // can choose to override method or not 
    }
}