In my UITableview I create a gradient layer and apply it to individual cells.

CAGradientLayer *gradient = [CAGradientLayer layer];
CGRect gradframe = CGRectMake(cell.frame.origin.x, cell.frame.origin.y, self.view.frame.size.width, cell.frame.size.height);
gradient.frame = gradframe;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:.9 green:.9 blue:.9 alpha:1.0] CGColor], (id)[[UIColor colorWithRed:.8 green:.8 blue:.8 alpha:1.0] CGColor], nil];

[cell setBackgroundView:[[UIView alloc] init]];
[cell.backgroundView.layer insertSublayer:gradient atIndex:0] ;

When I scroll offscreen and scroll back through my cells they lose their gradient layer.

I am still a bit new to ios development and any help will be appreciated.

EDIT: This will only happen sometimes. When scrolling up and down very occasionally there will be a cell that has the layer. And even these cells are not consistent.

有帮助吗?

解决方案

Try using cell.bounds instead of cell.frame, since the gradient frame should be relative to the cell. NSLog the gradient frame as shown below, and verify that the origin is {0,0}.

NSLog( @"%@", NSStringFromCGRect( gradient.frame ) );

Also, be careful, each time you pull a cell out of the reuse queue, it will still be configured as when it went into the reuse queue. So you need to make sure that you don't add a gradient to a cell that already has a gradient, or you could run into memory problems.


I think this is what you wanted for gradframe

CGRect gradframe = CGRectMake(0, 0, self.view.frame.size.width, cell.frame.size.height);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top