1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SwiftUIでLIstの背景色を変更する。

Last updated at Posted at 2022-06-17

はじめに

今回は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)
            }
        }
    }
}

フォーマットではグレーの背景色が適用されます。

背景色を変えてみよう!!

コード全文です。

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
    }
}

無事背景色を変更出来ました!!
extensionでメソッドを切り出す事で、backgroundColorとして設定出来るようにしました!!

以上です!!

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?