NRIネットコム Blog

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でのタイトルや背景色を変更することができます。
サンプルコードは以下の通りです。

  1. struct MySwiftUIView: View {
  2. init() {
  3. let navigationBarAppearance = UINavigationBarAppearance()
  4. navigationBarAppearance.configureWithOpaqueBackground()
  5. navigationBarAppearance.backgroundColor = UIColor.orange
  6. navigationBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.blue, .font : UIFont.systemFont(ofSize: 40)]
  7. navigationBarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white, .font : UIFont.systemFont(ofSize: 40, weight: .bold)]
  8. UINavigationBar.appearance().standardAppearance = navigationBarAppearance
  9. UINavigationBar.appearance().scrollEdgeAppearance = navigationBarAppearance
  10. UINavigationBar.appearance().compactAppearance = navigationBarAppearance
  11. }
  12. var body: some View {
  13. NavigationStack {
  14. Text("NavigationStack内の画面")
  15. .navigationTitle("test")
  16. .navigationBarTitleDisplayMode(.inline)
  17. }
  18. }
  19. }

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

コード 説明
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