如何在 iOS 上更改 TableView 项目的背景颜色?
iosapps/applicationsmobile development更新于 2026/2/12 6:52:17
更改 TableView 项目的背景颜色与更改 TableView 本身的背景颜色不同。新程序员经常会混淆这两者。在本文中,我们将了解如何更改 TableView 项目(即单元格)的背景颜色。
那么,让我们开始吧。
要更改 TableView 单元格的背景颜色,您应该更改单元格的 contentView.backgroundColor 属性。
在 cellForRowAt indexPath 方法中添加以下代码: cell.contentView.backgroundColor = UIColor.cyan
您的方法应该如下所示:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
cell.contentView.backgroundColor = UIColor.cyan
return cell
}
现在运行项目查看效果。


