Swift tableview单元重用问题

时间:2016-05-08 15:00:56

标签: arrays swift uitableview dictionary

我今天早上画了一个空白,可以使用一点指导。

我使用自定义表格单元格填充了一个包含字典数组的tableview。字典中的一个键值对是[“Time”],它在dicts数组中表示为:

"时间":" 12 am", "时间":“1 am", "时间":“2 am", "时间":“凌晨3点”等等......

这是我想做的事。

如果当前时间是凌晨1点(例如),我想更改该单元格的背景颜色。我使用下面粘贴的代码部分工作。当表视图加载时,正在突出显示正确的单元格,但是当我在表格视图中向上和向下滚动时,我看到其他行正在突出显示。我假设这与细胞如何重复使用有关。

其他信息: 1)“items”是我的字典数组 2)currentTime()只是一个小函数,以这种格式返回当前时间(“下午1点”)

有人能指出我正确的方向吗?

亲切的问候, 达林

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell:schedTableCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! schedTableCell
    cell.selectionStyle = .None

    // Highlight row where time value is equal to current time - THIS NEEDS WORK
    let showTime = self.items[indexPath.row]["time"] as! String
    if showTime == currentTime() {
        cell.backgroundColor = UIColor.greenColor()
    }

    cell.showTime.text = self.items[indexPath.row]["time"] as? String
    cell.showName.text = self.items[indexPath.row]["show"] as? String
    cell.showHost.text = self.items[indexPath.row]["host"] as? String

    return cell
}

1 个答案:

答案 0 :(得分:5)

确实,它是一种重用问题。执行此操作cell.backgroundColor = UIColor.greenColor()时,您将更改单元格背景颜色。但是当重复使用单元格时,您不会重置背景颜色,因此它会保持绿色!您可以像这样修复它(如果white是您的正常颜色):

   if showTime == currentTime() {
        cell.backgroundColor = UIColor.greenColor()
    } else {
        cell.backgroundColor = UIColor.whiteColor()
    }