I have a function that looks something like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// instantiate the cell
if(indexPath.row >=4 && indexPath.row <=5)
{
[CustomTableCell addGradient];
}
}
So basically, only rows 4 and 5 should have a gradient background. When the tableview first loads up, rows only rows 0 to 4 are visible and don’t have gradient background which is perfect. When I scroll a little down to see rows 4 and 5, the gradient appears on them, which is great again. but when I scroll back up to the first row, all of a sudden i see a gradient on the first row!!! But i never asked row 0 to have a gradient! Additionally, when i scroll down a bit, i see gradients applied to some rows and not others. Why is this happening?
here’s the addGradient function incase it’s useful:
- (void) addGradient
{
if([self.layer.sublayers count] >0)
{
if([[self.layer.sublayers objectAtIndex:0] isKindOfClass:[CAGradientLayer class]])
return;
}
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[UIColor blueColor].CGColor, (id)[UIColor redColor].CGColor, nil];
[self.layer insertSublayer:gradient atIndex:0];
}
I just realized that iPhone/cocoa is actually re-using an existing cell in memory for cellForRowAtIndexpath to draw cells that appear on screen. So that’s why the cell still has a gradient layer I had set before. So i updated my stylecell function to remove a layer if it exists, by using this code: