概要
複数のUIViewControllerを遷移中に、UINavigationBarの色(背景、タイトル、アイテム)を変え、
また元の色に戻します。
色を変えるのはすんなり出来たのですが、戻す際にタイトル色が戻らず、ハマってしまったのでメモとして残します。
遷移図
1→2に遷移する時に色が変わり、3は2と同じ色、2→1に戻るボタンで戻る際に、色を元に戻します。
コード
1つ目のViewController
FirstViewController.swift
// 一番目のViewController
class FirstViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "1"
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.barTintColor = nil // 背景色 デフォルト
navigationController?.navigationBar.tintColor = .black // アイテム色 黒
navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.black] //タイトル色 黒
}
}
2つ目のViewController
SecondViewController.swift
// 二番目のViewController
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "2"
navigationController?.navigationBar.barTintColor = .black // 背景色 黒
navigationController?.navigationBar.tintColor = .white // アイテム色 白
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
view.setNeedsUpdateConstraints()
view.updateConstraintsIfNeeded()
}
override func updateViewConstraints() {
super.updateViewConstraints()
navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white] //タイトル色 白
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// 遷移後の画面の為にここで設定
navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.black] //タイトル色 黒
}
}
3つ目のViewController
ThirdViewController.swift
// 三番目のViewController
class ThirdViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "3"
navigationController?.navigationBar.barTintColor = .black // 背景色 黒
navigationController?.navigationBar.tintColor = .white // アイテム色 白
navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white] //タイトル色 白
}
}
補足
背景色とアイテム色についてはviewWillAppearに書いておけば色が変わるのですが、
タイトル色についてはなぜかそれでは色が変わらない場合があるので、このような書き方をしています。
1と2の2画面だけの遷移の場合、viewDidLayoutSubviewsの部分の記載だけでも上手くいきます。
また、画面中で何か画面更新や他の動作が入る場合は上記コードだけでは上手くいかないかもしれません。
これがベストかどうかがわからない為、何か他に良い方法があれば教えていただけますと嬉しいです。