LoginSignup
3
3

More than 3 years have passed since last update.

iOS13で Navigation Bar のタイトルの色を変更する

Last updated at Posted at 2020-04-12

デベロッパー泣かせのダークモード

iOS13以降はダークモードに対応するようになりました。
それに合わせてデベロッパーもダークモードに対応することが推奨されています。
しかし、ダークモードの追加によって、アプリ内の文字色で今までと変化してしまう場所が出てきてしまいます。
その例がNavigation Barの文字部分等です。
StoryBoardで設定した色も無視されてしまいます。

【ダークモードオフ】
image.png
全く同じアプリですが、左がiOS13.4で右がiOS12.4です。
文字色が黒くなってしまいます。(Segueの表示の仕方等も変わっています。)

【ダークモードオン】
image.png
ダークモードをONにすることでやっとタイトルが白くなってくれました・・・

iOS13では自動的にダークモードに対応してくれるのですが、逆にそれが厄介なケースがあります。
それが今回のようにNavigationBarのタイトルを常に白色にしたい時です。

解決方法

英語記事を見つけましたが、日本語で解説しているサイトがないため解説していきます。
AppDelegate.swiftやViewControllerのviewDidLoad関数など、適当な場所以下のように記述します。(サンプルはviewDidLoadに記述した場合です。)

ViewController.swift
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        if #available(iOS 13.0, *) {
            let coloredAppearance = UINavigationBarAppearance()
            coloredAppearance.configureWithOpaqueBackground()
            coloredAppearance.backgroundColor = UIColor(red: 0, green: 192/255, blue: 192/255, alpha: 1) // 背景のRGBカラーコードを10進数で入力
            coloredAppearance.titleTextAttributes = [.foregroundColor: UIColor.white] // タイトルの色を指定
            coloredAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white] // タイトルの色を指定

            UINavigationBar.appearance().standardAppearance = coloredAppearance
            UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
        }   
    }

このようにすることでタイトルを常時指定した色にすることができます。
image.png

image.png

参考

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3