You are repeatedly setting the cells' colors.
Each time the table view wants to load a new cell, it calls its data sources' tableView(:cellForViewAtIndexPath:)
method.
In your implementation of this method, you loop through the array and set the color of the cell to each item of the array. So first it will be white, then black, then green... and finally it is set to clearColor
, which is transparent.
Every time that method gets called, your cells' colors will all be set to transparent. So sad!
By looking at your code, I think what you want is to set the first cell's color to white, the second to black, the third to green, etc.
You should know that each time tableView(:cellForRowAtIndexPath:)
is called, it provides you with an indexPath
argument that tells you which cell it wants. You just need to make use of that to implement your method:
// replace your for loop with this
cell.backgroundColor = colorArray[indexPath.row]
This way, when it wants the first cell, you set the cell to the first color. when it wants the second cell, you set the cell to the second color etc.
On the other hand, if you want to pick randomly from that colorArray
so the cells will be different each time the table view is loaded, you just need to generate a random number and call the subscript of colorArray
with that number:
// replace your for loop with this
let randomNumber = arc4random_uniform(UInt32(colorArray.count)) // line 1
cell.backgroundColor = colorArray[randomNumber] // line 2
line 1 generates a random number between 0 and colorArray.count
. And line 2 just sets the cell's color to the color at that index of colorArray
!
Straightforward, right?
EDIT: More about arc4random_uniform
You must be wondering what is this arc4random_uniform
function doing here.
arc4random_uniform
returns a random number (uniformly distributed) between 0 (inclusive) and the argument (exclusive). In other words, arc4random_uniform(5)
will return 0, 1, 2, 3, 4 but not 5.
The function takes a parameter of type UInt32
so I cannot pass in colorArray.count
directly.