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

Vik*_*eth 31 uitableview ios swift

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

Hom*_*mam 56

首先设置tableView的背景颜色viewDidLoad如下:

override func viewDidLoad() {
    super.viewDidLoad()   
    self.tableView.backgroundColor = UIColor.lightGrayColor()
}
Run Code Online (Sandbox Code Playgroud)

现在添加此方法:

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

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
}
Run Code Online (Sandbox Code Playgroud)

  • 大!谢谢!它工作,不知道为什么它不适用于Storyboard ..我只是在那里尝试...感谢您的帮助.. (3认同)
  • 应该编码为“ func tableView”,而不是“覆盖func tableView”。 (2认同)

Luc*_*rah 15

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.contentView.backgroundColor = UIColor.yellowColor()
}
Run Code Online (Sandbox Code Playgroud)

斯威夫特3

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


小智 7

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

Xcode中


IOS*_*ngh 5

使用此代码更改 tableView 颜色

override func viewDidLoad() {
        super.viewDidLoad()

       // define tableview background color
        self.tableView.backgroundColor = UIColor.clearColor()
}
Run Code Online (Sandbox Code Playgroud)

用于更改 tableView 单元格颜色

cell.backgroundColor = UIColor.clearColor()
Run Code Online (Sandbox Code Playgroud)