iOS Swift - 如何更改Table View的背景颜色?

问题描述 投票:29回答:6

我有一个简单的表格视图,我可以改变单元格的颜色,但是当试图改变表格视图(背景部分)的颜色时,它不起作用......我通过故事板尝试了...有人可以请帮助

ios uitableview swift
6个回答
52
投票

首先在viewDidLoad中设置tableView的背景颜色,如下所示:

override func viewDidLoad() {
    super.viewDidLoad()   
    self.tableView.backgroundColor = UIColor.lightGrayColor()
}

现在添加此方法:

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.backgroundColor = UIColor.clearColor()
}

在Swift 3中,使用以下方法而不是上面的方法:

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.backgroundColor = UIColor.lightGray
}

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

15
投票
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.contentView.backgroundColor = UIColor.yellowColor()
}

Swift 3

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

7
投票

如果你想通过storyboard实现,那么在tableView中选择“table view cell”的“Content View”,然后在属性Inspector中转到View并改变它的颜色,如下所示:

Xcode


4
投票

使用此代码更改tableView颜色

override func viewDidLoad() {
        super.viewDidLoad()

       // define tableview background color
        self.tableView.backgroundColor = UIColor.clearColor()
}

for change tableView单元格颜色

cell.backgroundColor = UIColor.clearColor()

0
投票

我比赛有点晚了!但是,上述答案都不适用于我,所以只是分享,我发现的工作,以防其他任何人跳过这个线程。

注意:我也有自己的自定义单元类。不确定这是否会影响您的代码!

@IBDesignable class YourViewController: UITableViewController {

//IBInspectable and IBDesignable makes the properties accessible in storyboard
@IBInspectable var tableViewBackground: UIColor?
@IBInspectable var cellViewBackground: UIColor?

//in case you want to customize the text color, as well!
@IBInspectable var customTextColor: UIColor?


override func viewDidLoad() {
//your code
self.tableView.backgroundColor = tableViewBackground
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath:    IndexPath) -> UITableViewCell {

    let cell = UITableViewCell()
    cell.textLabel?.textColor = customTextColor
    cell.backgroundColor = cellViewBackground
    return cell
}
//the rest of your code
}

找到你的检查:

1)。在tableView的viewController的Storyboard菜单中,单击yourViewController。 viewController中的第一个下拉列表。 (第一个下拉列表将包含tableView和cellView。它还可以包含其他好东西,具体取决于您的特定项目)。

2)。在属性检查器中,您将看到一个标题,其中包含viewController的名称和我们在上面定义的@IBInspectable属性!

3)。然后,您可以根据需要更改它们。

希望这可以帮助!


0
投票

你有:

  1. 细胞背景和
  2. Cell ContentView

将ContentView(如默认(透明))放在SB中,并放在awakeFromNib中的Cell方法中,只需:

self.backgroundColor = UIColor.SomeColor
© www.soinside.com 2019 - 2024. All rights reserved.