はじめに
今回はSwiftUIで多用されるであろうListの背景色を変更する手順を紹介したいと思います。
Listに対して.backgroundColorで変更したい所ですが、現状は対応していないようで、
UITableView.appearance() を使って変更します。
ContentView
import SwiftUI
struct MenuList: Identifiable {
var id = UUID()
var name : String
}
struct ContentView: View {
@State private var menuList = [
MenuList(name: "menu1"),
MenuList(name: "menu2"),
MenuList(name: "menu3"),
]
var body: some View {
List {
ForEach(menuList) { index in
Button(action: {
print("セルが押されました")
}) {
Text(index.name)
}
.foregroundColor(.black)
}
}
}
}
![](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F2428088%2Ff5bf71aa-8da0-f19f-f197-48f643c47d7e.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=2c43e959cad0527747037b7371a8cd66)
フォーマットではグレーの背景色が適用されます。
背景色を変えてみよう!!
コード全文です。
ContentView
import SwiftUI
struct MenuList: Identifiable {
var id = UUID()
var name : String
}
struct ContentView: View {
@State private var menuList = [
MenuList(name: "menu1"),
MenuList(name: "menu2"),
MenuList(name: "menu3"),
]
var body: some View {
List {
ForEach(menuList) { index in
Button(action: {
print("セルが押されました")
}) {
Text(index.name)
}
.foregroundColor(.black)
}
}
//追加
.backgroundColor(.blue)
}
}
//追加
extension List {
func backgroundColor(_ color: Color) -> some View {
UITableView.appearance().backgroundColor = UIColor(color)
return self
}
}
![](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F2428088%2Fa32e6204-eb00-f23e-771d-5c69cfeb9983.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=c37685e10a3816ed621b201d6a67bef5)
無事背景色を変更出来ました!!
extensionでメソッドを切り出す事で、backgroundColorとして設定出来るようにしました!!
以上です!!