2016-12-27 131 views
0

我有一个TableView并且在其中有一个单元格,我需要更改背景颜色。我试图寻找一个答案来改变单元格的背景颜色,但问题是,我发现每一个答案都必须做一个覆盖tableview函数,这将无法正常工作,因为我没有一个tableviewcontroller,而是它是一个嵌入了UITableView的普通视图控制器。 enter image description here在标准视图控制器中更改表格视图单元格'

如何简单地更改单元格的背景颜色?

+0

覆盖tableView函数是正确的。控制从tableView拖动到黄色按钮,并将委托和数据源设置为viewController。 – rMickeyD

回答

2

首先给你的表视图细胞通过分镜像这样的标识:

enter image description here

然后附加到vadian's answer访问您的像这样的tableView(_:cellForRowAt:) DataSource方法中的单元格并更新颜色,在示例中我将该方法放入扩展中:

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 
    } 

} 

另外不要忘记添加tableView(_:numberOfRowsInSection:)方法,以符合该UITableViewDataSource协议

像rMickeyD在评论中提到的,不要忘记设置你的表视图dataSourcedelegateCtrl + Drag从table view to the view controller like this:

enter image description here

3

这是无关紧要的,如果它是一个隐式或显式表视图。

cellForRowAtIndexPath设置单元格的属性backgroundColor

cell.backgroundColor = UIColor.orange 
相关问题