Changing a table view cell in a standard view cont

2019-09-11 08:17发布

I have a TableView and in it I have a cell that I need to change the background color of. I've tried searching for an answer to change the background color of the cell but the problem is that every answer I find has to do with an override tableview function, which will not work because I do not have a tableviewcontroller, rather it is a normal view controller with a UITableView embedded. enter image description here

How can I simply change the background color of the cell?

2条回答
老娘就宠你
2楼-- · 2019-09-11 08:35

First give your table view cell an Identifier via the storyboard like this:

enter image description here

Then additionally to vadian's answer access your cell in the tableView(_:cellForRowAt:) DataSource method like this and update the color, in the example I put the method in an extension:

extension ViewController: UITableViewDataSource {

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    cell.backgroundColor = UIColor.cyan

    return cell
  }

}

Also don't forget to add the tableView(_:numberOfRowsInSection:) method to conform the UITableViewDataSource protocol

Like rMickeyD mentioned in the comments, don't forget to set your table view as dataSource and delegate with Ctrl + Drag from the table view to the view controller like this:

enter image description here

查看更多
放我归山
3楼-- · 2019-09-11 08:51

It doesn't matter if it's an implicit or explicit table view.

In cellForRowAtIndexPath set the property backgroundColor of the cell:

cell.backgroundColor = UIColor.orange
查看更多
登录 后发表回答