Swift tableview单元重用问题

Dar*_*rin 3 arrays dictionary uitableview swift

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

我正在使用自定义表格单元格填充带有一系列字典的tableview.字典中的一个键值对是["Time"],它在dicts数组中表示为:

"时间":"上午12点","时间":"凌晨1点","时间":"凌晨2点","时间":"凌晨3点"等等......

这是我想做的.

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

附加信息:1)"items"是我的字典数组2)currentTime()只是一个小函数,以这种格式返回当前时间("1pm")

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

亲切的问候,达林

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
}
Run Code Online (Sandbox Code Playgroud)

Jul*_*ere 5

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

   if showTime == currentTime() {
        cell.backgroundColor = UIColor.greenColor()
    } else {
        cell.backgroundColor = UIColor.whiteColor()
    }
Run Code Online (Sandbox Code Playgroud)