有没有办法在 SwiftUI 中更改列表行的背景?

Is there a way to change the background of List rows in SwiftUI?

我想在 SwiftUI 中更改列表行的背景颜色,但不太明白。这是我目前编写的代码的一个更简单的版本。

struct ContentView: View {
    init() {
        UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.black]
        UINavigationBar.appearance().barTintColor = .blue
    }
    
    var body: some View {
        NavigationView {
            ZStack {
                HStack {
                    List(0...10) { test in
                        Spacer()
                            self.background(Color.purple)
                        Text("This is a test")
                        Spacer()
                        self.background(Color.pink)
                    }
                    .background(Color.blue)
                    List(0...10) { test2 in
                        Spacer()
                        Text("Also a test")
                            .background(Color.green)
                        Spacer()
                    }
                    .background(Color.red)
                }
            }
        }
        .navigationBarTitle(
            Text("Test"),
            displayMode: .inline
        )
    }
}

我只希望 cell/row 背景改变颜色,但它们在浅色模式下保持白色,在深色模式下保持黑色。

你可以使用 .colorMultiply() 属性,

代码已更新 XCode 11.

检查下面的代码:

init() {
        UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.black]
        UINavigationBar.appearance().barTintColor = .blue
    }

    var body: some View {

    NavigationView {
        VStack {
            HStack {
                List(0..<10) { test1 in
                    Spacer()
                    Text("This is a test1")
                    Spacer()
                }.colorMultiply(Color.pink)

                List(0..<10) { test2 in
                    Spacer()
                    Text("This is a test2")
                        .background(Color.green)
                    Spacer()
                }.colorMultiply(Color.green)
            }.padding(.top)
        }.navigationBarTitle(Text("Test"), displayMode: .inline)
    }

}

输出:

我在使用列表和部分时发现的一件事是它们是元组视图类型,即它们不是单一视图,并且像 border() 和 background() 这样的东西适用于列表中的元素,而不是列表本身。要创建单个视图进行修改,您需要将它们嵌入到堆栈中。