首页 > 解决方案 > 在 SwiftUI 中更改 UITableViewCell 背景颜色

问题描述

我使用列表来显示动态数量的自定义视图。见代码。

 @State var coins : [Coin]
var coinList : some View {
        List {
            ForEach(0..<coins.count, id: \.self) { i in
                    CoinEntry(coin: coins[i])
                }.onDelete(perform: { indexSet in
                    self.coins.remove(atOffsets: indexSet)
                })
        }.frame(width: UIScreen.main.bounds.width)
    }

在那之后,我有了这个清单。

在此处输入图像描述

之后,我像这样修改了列表。

UITableView.appearance().backgroundColor = UIColor.clear
UITableViewCell.appearance().backgroundColor = UIColor.clear

列表底部现在已更改为清除,但单元格仍然是白色的。

在此处输入图像描述

如果我这样编辑它:

CoinEntry(coin: coins[i]).background(MAIN_DARK_GRAY)

该列表如下所示:

在此处输入图像描述

希望有人能帮忙!

标签: iosswiftswiftui

解决方案


只需添加 .background 属性即可更改视图的背景颜色

var coinList : some View {
    List {
        ForEach(0..<coins.count, id: \.self) { i in
                CoinEntry(coin: coins[i]).background(MAIN_DARK_GRAY)
            }.onDelete(perform: { indexSet in
                self.coins.remove(atOffsets: indexSet)
            })
    }.frame(width: UIScreen.main.bounds.width).background(MAIN_DARK_GRAY)
}

或者您可以使用 listRowBackground 属性

var coinList : some View {
    List {
        ForEach(0..<coins.count, id: \.self) { i in
                CoinEntry(coin: coins[i])
            }.onDelete(perform: { indexSet in
                self.coins.remove(atOffsets: indexSet)
            })
    }.frame(width: UIScreen.main.bounds.width).listRowBackground(MAIN_DARK_GRAY)
}

推荐阅读