ios - 如何在所有视图控制器的导航栏中添加一个通用按钮?
问题描述
我想在我的应用程序的所有视图控制器中添加/删除导航栏中的按钮作为子视图。如何将此添加/删除移动到公共代码,以便我可以减少更新现有代码以实现此功能的工作?
我知道我可以在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
}
}
解决方案
您可以为所有需要按钮的类创建父视图控制器。
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
}
}
推荐阅读
- javascript - 在 CMS 中创建过滤系统的最佳逻辑是什么,然后添加选项来选择显示多少过滤结果?
- flutter - 如何清除除颤动中的 2 个键之外的所有 SharedPreferences 键
- c++ - 从向量中提取最小值、最大值和中值的最有效方法是什么
- oracle - 如何解决redhat linux中创建数据库文件错误
- c# - 如何替换字符串c#开头的所有换行符
- java - Spring Data REST 在运行时选择字段
- javascript - 如何通过在 MarkLogic 中传递 URI 和集合名称来搜索文档?
- c - 提高我实现计数排序 (C) 的时间复杂度
- excel - 在用户窗体的列表视图中更改单个项目的颜色
- react-native-android - 无法安装反应导航