NRIネットコム社員が様々な視点で、日々の気づきやナレッジを発信するメディアです

注目のタグ

    【SwiftUI】NavigationView及びNavigationStackのタイトルや背景色を変更する方法

    概要

    NavigationViewやNavigationStackのタイトルや背景色を変更する方法をご紹介します。

    環境

    この記事は以下のバージョン環境のもと作成されたものです。
    【Xcode】14.1
    【iOS】16.1
    【macOS】Monterey バージョン 12.6

    実装方法

    UINavigationBarAppearanceはナビゲーションバーの外観をカスタマイズするためのオブジェクトです。

    https://developer.apple.com/documentation/uikit/uinavigationbarappearance

    そのUINavigationBarAppearanceを使用する事でSwiftUIのNavigationViewやNavigationStackでのタイトルや背景色を変更することができます。
    サンプルコードは以下の通りです。

    struct MySwiftUIView: View {
        init() {
            let navigationBarAppearance = UINavigationBarAppearance()
            navigationBarAppearance.configureWithOpaqueBackground()
            navigationBarAppearance.backgroundColor = UIColor.orange
            navigationBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.blue, .font : UIFont.systemFont(ofSize: 40)]
            navigationBarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white, .font : UIFont.systemFont(ofSize: 40, weight: .bold)]
            UINavigationBar.appearance().standardAppearance = navigationBarAppearance
            UINavigationBar.appearance().scrollEdgeAppearance = navigationBarAppearance
            UINavigationBar.appearance().compactAppearance = navigationBarAppearance
        }
        var body: some View {
            NavigationStack {
                Text("NavigationStack内の画面")
                    .navigationTitle("test")
                    .navigationBarTitleDisplayMode(.inline)
            }
        }
    }
    

    サンプルコードの各解説は以下の通りです。

    コード 説明
    configureWithOpaqueBackground このメソッドを呼び出すと、以前の値がリセットされる。
    backgroundColor 背景色の変更。
    titleTextAttributes navigationBarTitleDisplayModeがinline時のフォント色及びサイズの変更。
    largeTitleTextAttributes navigationBarTitleDisplayModeがLarge及びautomatic時のフォント色及びサイズの変更。
    appearance().standardAppearance 標準の高さのナビゲーションバーの外観設定。
    appearance().scrollEdgeAppearance スクロール可能なコンテンツの端がナビゲーションバーの端に揃うときのナビゲーションバーの外観設定。
    NavigationViewやNavigationStackで使用する際はscrollEdgeAppearanceに必ず反映させる必要があります。
    appearance().compactAppearance コンパクトな高さのナビゲーションバーの外観設定。

    これでタイトルや背景色を変更する事ができます。

    まとめ

    UINavigationBarAppearanceを使用する事でNavigationView及びNavigationStackのタイトルや背景色を変更する方法の紹介でした。 また公式よりサンプルコードも提供されているので、より深く知りたい方はご参照ください。

    https://developer.apple.com/documentation/uikit/uinavigationcontroller/customizing_your_app_s_navigation_bar

    執筆者岡優志

    iOSエンジニア
    iOSを専門とし、モバイルアプリの開発を行なっています。

    Twitter