- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
在我的应用程序中,我在 UINavigationController
中嵌入了许多 UIViewControllers
,其中包含一个 cancel rightBarButtonItem
和 保存 leftBarButtonItem
。
在每个类中,我都有重复的代码来自定义栏按钮项的属性:
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)
在 AppDelegate 中,我可以更改栏按钮项,这会同时影响 leftBarButtonItem
和 rightBarButtonItem
:
UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: fontFuturaMedium,
size: fontSize17)!],
for: .normal)
但是,我想独立地更改两个按钮,从而影响所有 View Controller ,而不必重复代码。
我试图访问 UINavigationItem
的 leftBarButtonItem
属性,但它不存在。 UINavigationItem
也没有 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)
}
这显然更容易并且减少了很多重复代码,因为我可以在我的所有类中调用那一行代码。
但是,是否有一个我可以放入 AppDelegate 的单行代码,它将在整个所有 类中复制,类似于 UIBarButtonItem.appearance()。 setTitleTextAttributes
,而不是在所有类中调用 setNavBar
?
谢谢。
最佳答案
我会子类化一个UIViewController
,也许叫它BaseViewController
;在基本 View Controller 的 viewDidLoad
中,我将放置所有设置内容(基本上是您在 setNavBar
中所做的)。
然后,项目的每个 View Controller 都将扩展基础 View Controller 。
关于ios - 如何为 AppDelegate 中的所有 View Controller 独立更改左右栏按钮项文本属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50869785/
我是一名优秀的程序员,十分优秀!