如何为AppDelegate中的所有View控制器独立更改左右栏按钮项文本属性?

时间:2018-06-15 05:50:59

标签: ios swift uinavigationitem

在我的应用中,我在UIViewControllers中嵌入了很多UINavigationController,其中包含取消 rightBarButtonItem保存 {{1 }}

在每个班级中,我都有重复的代码来自定义栏按钮项的属性:

leftBarButtonItem

AppDelegate 中,我可以更改条形按钮项,这会同时影响navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: fontFuturaMedium, size: fontSize17)! ], for: .normal) navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: fontFuturaMedium, size: fontSize17)! ], for: . highlighted) navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: fontFuturaBold, size: fontSize19)! ], for: .normal) navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: fontFuturaBold, size: fontSize19)! ], for: . highlighted) leftBarButtonItem

rightBarButtonItem

但是,我想更改两个按钮独立,影响所有视图控制器,而不必重复代码。

我尝试访问UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: fontFuturaMedium, size: fontSize17)!], for: .normal) 的{​​{1}}属性,但它不存在。 leftBarButtonItem也没有UINavigationItem属性。

我已将重复代码放在全局函数中:

UINavigationItem

这显然更容易,减少了很多重复的代码,因为我可以在所有我的类中调用一行代码。

但是,是否有一个单行代码可以放入 AppDelegate ,它将在所有类中复制,类似于appearance(),而不是调用所有课程都是static public func setNavBar(viewController: UIViewController) { viewController.navigationItem.leftBarButtonItem?.setTitleTextAttributes( [NSAttributedStringKey.font: UIFont(name: fontFuturaMedium, size: fontSize17)! ], for: .normal) viewController.navigationItem.leftBarButtonItem?.setTitleTextAttributes( [NSAttributedStringKey.font: UIFont(name: fontFuturaMedium, size: fontSize17)! ], for: .highlighted) viewController.navigationItem.rightBarButtonItem?.setTitleTextAttributes( [NSAttributedStringKey.font: UIFont(name: fontFuturaBold, size: fontSize19)! ], for: .normal) viewController.navigationItem.rightBarButtonItem?.setTitleTextAttributes( [NSAttributedStringKey.font: UIFont(name: fontFuturaBold, size: fontSize19)! ], for: .highlighted) }

感谢。

1 个答案:

答案 0 :(得分:0)

我会升级UIViewController,也许称之为BaseViewController;在基本视图控制器的viewDidLoad中,我将放置所有设置内容(基本上是您在setNavBar中执行的操作)。

然后,项目的每个视图控制器都将扩展基础视图。