Reputation: 4077
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.
In my cellForRowAtIndexPath
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).
Here is my current global 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),
]
Then here is the portion from cellForRowAtIndexPath
which sets the colours based on the collection size:
// 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 > totalColors) {
let diff = Int(ceil(CGFloat(totalCells) / CGFloat(totalColors)))
if(currDiff > diff) {
currDiff = 0
currIndex++
}
if currIndex < 0 {
currIndex = 0
}
if(currIndex >= bgColors.count) {
currIndex = 0
}
cell.backgroundColor = bgColors[currIndex]
currDiff++
} else {
cell.backgroundColor = bgColors[indexPath.row]
}
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.
I hope this makes sense, if any further details are needed please ask.
Upvotes: 0
Views: 16
Reputation: 318934
Since you want the colors evenly distributed through the rows of the table, you can do some simple math on the cell's indexPath.row
to calculate the needed color index.
I'm not proficient in Swift so the following syntax could be a bit off but it should be close:
var colorIndex = Int((CGFloat(indexPath.row) / CGFloat(tasks.count)) * CGFloat(bgColors.count));
The first part gives you the percentage through the table for the given row and then that percentage is applied to the color count.
Keep in mind that if the number of rows isn't a whole multiple of the color count, then obviously not every color will appear the same number of times.
Upvotes: 1