title: iOS: How to ensure cell maintains its colour when reuse cells are on
body: <p>I'm building an app where my tableview cells transition in colour from Red to Dark blue (Hot to Cold), this dictates an order of priority for tasks to be completed in.</p>
  
  <p>In my <code>cellForRowAtIndexPath</code> method, I have written some logic to ensure that the color of each cell is equal depending on the size of a task collection.  The problem I am facing is that my global variables which track the current index mutate each time a new cell is generated, meaning my cells all become one block color at some given point (as the user scrolls).</p>
  
  <p>Here is my current global code:</p>
  
  <pre><code>// Difference is calculated by dividing the bgColors size by the task collection size
  var currDiff = 0
  var currIndex = 0
  
  var tasks = [PFObject]()
  var bgColors = [
      UIColor(red: 255, green: 51, blue: 51),
      UIColor(red: 255, green: 153, blue: 51),
      UIColor(red: 255, green: 255, blue: 51),
      UIColor(red: 153, green: 255, blue: 51),
      UIColor(red: 102, green: 255, blue: 51),
      UIColor(red: 51, green: 255, blue: 204),
      UIColor(red: 51, green: 204, blue: 255),
      UIColor(red: 51, green: 102, blue: 255),
  ]
  </code></pre>
  
  <p>Then here is the portion from <code>cellForRowAtIndexPath</code> which sets the colours based on the collection size:</p>
  
  <pre><code>    // Compute the cell colour
      let totalCells = tasks.count
      let totalColors = bgColors.count
  
      // If we exceed the number of colours, then evenly distribute them
      if(totalCells &gt; totalColors) {
          let diff = Int(ceil(CGFloat(totalCells) / CGFloat(totalColors)))
          if(currDiff &gt; diff) {
              currDiff = 0
              currIndex++
          }
  
          if currIndex &lt; 0 {
              currIndex = 0
          }
          if(currIndex &gt;= bgColors.count) {
              currIndex = 0
          }
  
          cell.backgroundColor = bgColors[currIndex]
          currDiff++
      } else {
          cell.backgroundColor = bgColors[indexPath.row]
      }
  </code></pre>
  
  <p>In the scenario that I had 28 tasks in a collection and 8 colors, this code would compute 28 / 8 = 3.5 and then round it to 4, this would then render blocks of 4 by using currDiff to track the amount of cells rendered in that specific colour, and currIndex to track which index in the array we are.</p>
  
  <p>I hope this makes sense, if any further details are needed please ask.</p>