首页 > 解决方案 > 如何在所有视图控制器的导航栏中添加一个通用按钮?

问题描述

我想在我的应用程序的所有视图控制器中添加/删除导航栏中的按钮作为子视图。如何将此添加/删除移动到公共代码,以便我可以减少更新现有代码以实现此功能的工作?

我知道我可以在UIViewController扩展中添加添加/删除函数,然后从每个 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
    }
}

标签: iosswiftuinavigationcontrollernavbar

解决方案


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

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

其他类可以继承它,也可以覆盖这些方法。

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

推荐阅读