【问题标题】:Change background color of even cells in tableView更改tableView中偶数单元格的背景颜色
【发布时间】:2016-03-20 00:39:00
【问题描述】:

我无法更改 tableView 中偶数单元格的背景颜色。当视图加载时,单元格的颜色正确,但当我滚动时,背景颜色变为白色或全部为浅灰色。

我应该以其他方式更新背景颜色吗?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("gradeCell", forIndexPath: indexPath)

    if ( indexPath.row % 2 == 0) {
        cell.backgroundColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1.0)
    }
    return cell
}

【问题讨论】:

  • 如果行不均匀则需要将背景颜色设置回原来的颜色
  • prepareForReuse
  • 谢谢,忘记细胞被重复使用了

标签: ios swift uitableview tableview


【解决方案1】:

把这段代码sn-p。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("gradeCell", forIndexPath: indexPath)

    if (indexPath.row % 2 == 0) {
      cell.backgroundColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1.0)
    }else{
      cell.backgroundColor = UIColor.whiteColor() // set your default color
    }

    return cell
  }

【讨论】:

    猜你喜欢
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 2013-04-12
    • 2021-10-31
    • 2017-11-02
    相关资源
    最近更新 更多