ナビゲーションのタイトルカラーを画面ごとに変更する

バージョン

  • Xcode Version 10.0 (10A255)
  • Swift4.2

やりたいこと

  • 最初の画面はタイトルカラー赤
  • 遷移先の画面はタイトルカラー青

実装1

ググるととよく出てくるやつ。

ただ、これだと最初の画面に戻った時に青のままです。

遷移元ViewController

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "ViewController1"
        navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.red]
    }

    // 省略
}

遷移先ViewController

class ViewController2: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "ViewController2"
        navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.blue]
    }

    // 省略
}

実装2

同僚氏に教えてもらいました。

遷移先の willMove(toParent:) で元の色に戻してやれば、最初の画面に戻った時に赤に戻ります。

遷移元ViewController

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "ViewController1"
        navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.red]
    }

    // 省略
}

遷移先ViewController

class ViewController2: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "ViewController2"
        navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.blue]
    }

    override func willMove(toParent parent: UIViewController?) {
        super.willMove(toParent: parent)
        navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.blue]
    }

    // 省略
}

他にもいろいろ試行錯誤したけど、これが一番まともでした。

ほんとは遷移してきた時点で前の画面のタイトルカラーを保存して戻してやりたかったんだけど、遷移してきたときには nil っぽかった。

なんかいい方法知ってたら教えてください。

試行錯誤の残骸です。

GitHub - y-sumida/NavigationTitleColorSample: ナビゲーションバーのタイトルカラーをページごとに変更する