问题
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.
How can I simply change the background color of the cell?
回答1:
First give your table view cell an Identifier via the storyboard like this:
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:
回答2:
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
来源:https://stackoverflow.com/questions/41350278/changing-a-table-view-cell-in-a-standard-view-controller