如何在所有视图控制器的导航栏中添加通用按钮?

问题描述 投票:0回答:1

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

我知道我可以在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
    }
}
ios swift uinavigationcontroller navbar
1个回答
0
投票

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

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 
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.