Duplication in values of tableView when Scrolling Swift

后端 未结 3 1198
情深已故
情深已故 2021-01-14 06:33

I have a tableView to display timings of week days

timingsArray is used in tableView to display timings

timingsArray of type timingObj

cla         


        
3条回答
  •  隐瞒了意图╮
    2021-01-14 07:12

    From the Apple Docs:

    At runtime, the table view stores cell objects in an internal queue. When the table view asks the data source to configure a cell object for display, the data source can access the queued object by sending a dequeueReusableCellWithIdentifier: message to the table view, passing in a reuse identifier. The data source sets the content of the cell and any special properties before returning it. This reuse of cell objects is a performance enhancement because it eliminates the overhead of cell creation.

    So what you're doing when reusing cells from the queue is retrieving cells you have already created and configured. Changes made to the created Cells will be also applied to the reused cells which are displayed when scrolling as soon as the reused cells aren't visible anymore. This means you have to re-assign any values you want to override which are custom to the unique cell you are displaying, which also applies if there is no content/an empty string you want to display. Otherwise you will get random results as you have been experiencing.

    let cell = tableView.dequeueReusableCellWithIdentifier("TimingsCell", forIndexPath: indexPath) as! timingCell     
    let timings = self.Details!.timingsArray
    let dayTime = timings[indexPath.row]
    cell.dayLabel.text = dayTime.dayName
    
    if dayTime.open != nil && dayTime.close != nil {
        cell.timeLabel.text = "\(convertTimeFormat(dayTime.open!)) - \(convertTimeFormat(dayTime.close!))"
    }
    else{
     //change label to empty string when reusing
     cell.timeLabel.text = "";
    }
    
    return cell
    

提交回复
热议问题