Changing a table view cell in a standard view controller'

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-25 08:24:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!