【问题标题】:Set background color of UITableView programmatically not working以编程方式设置 UITableView 的背景颜色不起作用
【发布时间】:2026-02-14 10:55:01
【问题描述】:

我使用故事板添加了一个 UIView 并将其子类化。在这个视图中,我以编程方式添加了一个 UITableView。下面是创建tableview并添加它的代码:

private func commonInit() {
    self.backgroundColor = .clear

    self.categoryTableView = UITableView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height))

    categoryTableView?.delegate = self
    categoryTableView?.dataSource = self

    self.categoryTableView?.backgroundView = nil
    self.categoryTableView?.backgroundColor = .yellow

    self.categoryTableView?.isScrollEnabled = false
    self.categoryTableView?.allowsMultipleSelection = true

    self.addSubview(categoryTableView!)
}

这就是它的样子。我期望 tableview 的背景是黄色的(在屏幕截图中是白色的)

我还将单元格背景颜色设置为清除,这似乎可以正常工作。当我查看 UI 层次结构时,很明显 White 来自 tableview。

我觉得这应该是非常困难的。奇怪的是self.categoryTableView?.isScrollEnabled = falseself.categoryTableView?.allowsMultipleSelection = true 这两条线似乎都在工作,但背景颜色的变化却没有。

【问题讨论】:

  • 设置主线程背景色
  • @BadhanGanesh 是的,修复了它。谢谢!

标签: ios swift uitableview uiview


【解决方案1】:

我在操场上测试了这个,结果和预期的一样。

import UIKit
import XCTest
import PlaygroundSupport


let view = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
PlaygroundPage.current.liveView = view

view.backgroundColor = UIColor.blue

let tableView = UITableView(frame:CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))
tableView.backgroundColor = UIColor.yellow
view.addSubview(tableView)

结果:

我的猜测是这里正在发生其他事情。可能与框架大小有关,或者您在哪里调用 commonInit() 方法?

【讨论】:

  • commonInit() 是从 required init?(coder aDecoder: NSCoder) 调用的。我认为这可能是问题的一部分,因为在主线程中设置背景颜色(就像@Badhan Ganesh 建议的那样)似乎已经解决了这个问题。也许从 required init?(coder aDecoder: NSCoder) 调用函数会使其在 UI 线程以外的线程上运行。
【解决方案2】:

我遇到了完全相同的问题,发现只是在tableView.backgroundView = nil 之后更改tableView.backgroundColor 不起作用。

我的案例也是在UIView 中以编程方式创建的UITableView

解决方案是在tableView 中添加一个backgroundView 并更改backgroundView 对象的属性backgroundColor


Swift 5 / iOS 12.x

改变 tableView 背景颜色

对于.clear 以外的任何颜色,上述方法都应该有效:

    self.tableView.backgroundView = UIView() //Create a backgroundView
    self.tableView.backgroundView!.backgroundColor = .lightGray //choose your background color

改变 tableViewCells 背景颜色

再进一步,有些人可能会发现 tableView 背景颜色没有按预期显示,因为 UITableViewCell 实例的背景颜色。确保单元格具有透明背景的简单解决方案:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        cell.contentView.backgroundColor = UIColor.clear
        cell.backgroundColor = .clear
    }

【讨论】:

  • 要使其与.clear 一起使用,请将您的背景视图定义为UIView(frame: .infinite)