【SwiftUI】
NavigationBarの背景色を変更する方法
UINavigationBarの変更
投稿日 2021/03/11 更新日 2021/09/26

こんにちは。当サイトの管理者「元木皇天」です。
今回はSwiftUIのNavigationBarの背景色を簡単に変える方法をご紹介したいと思います。
環境
OS:MacOS Big Sur
Xcode:バージョン12.3
Swift:バージョン5.3
やりたいこと
SwiftUIのNavigationBarの背景色を変更する。(以下イメージ画像)

NavigationBarの背景色の設定方法
NavigationBarの背景色の設定するにはinit()にNavigationBarの背景色を変更する処理を記述します。
以下のコードがNavigationBarの背景色を変更するコードです。(ここでは緑色に変更しています。)
init(){ //ナビゲーションバーの背景色の設定 UINavigationBar.appearance().barTintColor = UIColor.green }
次の項目にて、実際の使用例と変更結果を解説いたします。
実際の使用例
まずは、ContentViewにNavigationBarを配置しましょう。
import SwiftUI struct ContentView: View { var body: some View { NavigationView(){ VStack(){ NavigationLink(destination: ContentView()){ Text("ナビゲーションビュー") } } .navigationBarTitle("ナビゲーション", displayMode: .inline) } } }
実際に画面を起動すると以下のようになります。

デフォルトではNavigationBarの背景色は白色です。
今回はこちらを緑色に変えてみましょう。
先程のコードに、init()を追加して、そこに先程のNavigationBarの背景色を変更するコードを記述します。
import SwiftUI struct ContentView: View { init(){ //ナビゲーションバーの背景色の設定 UINavigationBar.appearance().barTintColor = UIColor.green } var body: some View { NavigationView(){ VStack(){ NavigationLink(destination: ContentView()){ Text("ナビゲーションビュー") } } .navigationBarTitle("ナビゲーション", displayMode: .inline) } } }
実際に画面を起動すると以下のようにナビゲーションバーの背景色が変わっていることがわかります。

まとめ
SwiftUIのNavigationBarの背景色を変更するにはUINavigationBar.appearance().barTintColor を使用します。