如何再次更改UINavigationBar标题文本的颜色

时间:2018-08-08 16:06:18

标签: ios uinavigationbar

这是这里的示例。我想将全局UINavigationBar背景颜色更改为黄色,并将标题文本颜色更改为黑色。因此,我在下面的AppDelegate.swift中编写了这段代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    UINavigationBar.appearance().isTranslucent = false
    UINavigationBar.appearance().shadowImage = UIImage()
    UINavigationBar.appearance().barTintColor = UIColor.yellow
    UINavigationBar.appearance().tintColor = UIColor.black
    UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.black]

    return true
}

此代码运行良好。现在我有三个ViewController。第一个和第三个使用全局导航栏外观。但是第二个我希望它是蓝色的。所以我在SecondViewController中有这段代码:

class SecondViewController: UIViewController {
  private let originBarTintColor = UINavigationBar.appearance().barTintColor
  private let originTintColor = UINavigationBar.appearance().tintColor
  private let originTitleAttributes = UINavigationBar.appearance().titleTextAttributes
  private let originStatusBarStyle = UIApplication.shared.statusBarStyle
  private let titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]

  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    navigationController?.navigationBar.barTintColor = UIColor.blue
    navigationController?.navigationBar.tintColor = UIColor.white
    navigationController?.navigationBar.titleTextAttributes = self.titleTextAttributes

    UIApplication.shared.statusBarStyle = .lightContent
  }

  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    navigationController?.navigationBar.barTintColor = originBarTintColor
    navigationController?.navigationBar.tintColor = originTintColor
    navigationController?.navigationBar.titleTextAttributes = originTitleAttributes

    UIApplication.shared.statusBarStyle = originStatusBarStyle
  }

}

现在是问题所在。第一次从FirstVC推送SecondVC和从SecondVC推送ThirdVC,一切都很好。但是当弹出时,titleTextAttributes不起作用。这是gif:

enter image description here

我不想在ThirdVC的willMoveToParent()中设置titleTextAttributes,因为SecondVC可以使用任何VC并从任何其他视图控制器弹出。因此,如果可以修复此问题,那么仅在SecondVC中应该更好。

有人能告诉我当弹出SecondVC时如何解决导航栏标题文本的颜色吗?

0 个答案:

没有答案