【SwiftUI】
Listの背景色を変更する方法
listRowBackgroundとUITableViewの設定
投稿日 2021/03/14 更新日 2021/09/26

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


Listのセル単体の背景色の変更
Listのセル単体とはなんだ?と思う方もいるかもしれないので、説明すると以下の赤で囲んだところを指しています。
ここをなんて呼ぶのか知ってたらTwitterのDMとかでこっそり教えてください...。

ここの背景色を変更するには.listRowBackground(Color.XXX)を使用します。(XXXには設定したい背景色を入れます。)
以下が実際に使用した例です。
import SwiftUI struct ContentView: View { var body: some View { List{ Text("Test1") .listRowBackground(Color.red) Text("Test2") .listRowBackground(Color.blue) Text("Test3") .listRowBackground(Color.green) Text("Test4") .listRowBackground(Color.gray) Text("Test5") .listRowBackground(Color.yellow) } } }
画面を表示すると以下のように背景色が変わっていることがわかります。

List全体の背景色の変更
List全体の背景色を変更するためにはUITableView.appearance().backgroundColorを使用します。
実際の変更イメージは以下の通りです。

先程のUITableViewのコードをinit()内で使用することで、List全体の背景色を変更することができます。
以下がList全体の背景色の変更を実装したコードです。
import SwiftUI struct ContentView: View { init(){ //List全体の背景色の設定 UITableView.appearance().backgroundColor = UIColor.lightGray } var body: some View { List{ Text("Test1") Text("Test2") Text("Test3") Text("Test4") Text("Test5") } } }
実際に画面を起動すると以下のようになります。

まとめ
SwiftUIのListの背景色を変更するにはlistRowBackgroundとUITableView.appearance().backgroundColor を使用します。