选中或突出显示时,全局更改UIBarButtonItem文本颜色

时间:2017-08-30 13:41:24

标签: ios swift uibarbuttonitem

我有UIToolbar(在我的UINavigationController内)并且有一些UIBarButtonItem s。

工具栏为blueisTranslucent = false),按钮为white。默认突出显示颜色为gray,看起来很丑。

我找到的唯一解决方案是在UIBarButtonItem触摸事件中更改tintColor&#39 {s} @IBAction。但是我有很多UIBarButtonItem个,而且每个@IBAction编写大量代码都很烦人。

你知道如何全局更改它,或者至少是子类UIBarButtonItem来定义它并在任何地方使用这个类吗?

我使用swift 3,部署目标是iOS 9 +

3 个答案:

答案 0 :(得分:4)

您的didFinishLaunchingWithOptions女巫中有AppDelegate个功能,告诉代表启动过程已基本完成且应用程序已准备就绪。

在那里,您可以使用appearanceUIBarButtonItem上的UINavigationBar

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Text
    UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.green], for: .normal)
    UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.darkGray], for: .selected)

    // Images
    UINavigationBar.appearance().tintColor = UIColor.orange

    return true
}

<强>结果:
enter image description here

答案 1 :(得分:3)

您可以使用appearance全局更改颜色。在<x json="{&quot;connection&quot;:&quot;a=\&quot;b\&quot;&quot;}"/> 方法

中添加下一行
didFinishLaunchingWithOptions

答案 2 :(得分:0)

Swift 4.2

UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIColor.green], for: .normal)
UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIColor.darkGray], for: .selected)