0

I'm using the CAGradientLayer method from this answer to set a gradient on my UITableViewCells.

However, for this table, I increased the height of the cells via tableView:heightForRowAtIndexPath:. My gradient layer now does not cover the full height of cell, but instead stops at the original height (see pic).

I tried setting the frame of the layer to the cell bounds in tableView:cellForRowAtIndexPath: but that didn't work either. Is there some way to specify the layer should be autoresized?

Thanks!

Code:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        CAGradientLayer *gradient = [CAGradientLayer layer];
        gradient.colors = [NSArray arrayWithObjects:
                           (id)[[UIColor purpleColor] CGColor],
                           (id)[[UIColor redColor] CGColor],
                           nil];
        [cell.layer insertSublayer:gradient atIndex:0];
    }
    cell.layer.borderWidth = 1.0;
    CALayer* gradientLayer = [cell.layer.sublayers objectAtIndex:0];
    DebugLog(@"cell bounds: %@", NSStringFromCGRect(cell.bounds));
    gradientLayer.frame = cell.bounds;

    // Configure the cell...
    return cell;
}
Community
  • 1
  • 1
initlaunch
  • 467
  • 5
  • 15

3 Answers3

2

Had this problem if your cell height is coded as 55 then you should do the below this will then fill the cell for this table.

    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = CGRectMake(0, 0, 320, 55);

dont do

    gradientLayer.frame = cell.bounds;
Alex McPherson
  • 3,185
  • 3
  • 30
  • 41
  • @Alex McPherson, Is there any specific reason why should not assign cell's bound to gradient layer's frame? – Ganpat Mar 02 '19 at 05:41
0

I think you're going the wrong way to customize your table cells. See the http://cocoawithlove.com/2009/04/easy-custom-uitableview-drawing.html.

MrZoidberg
  • 350
  • 3
  • 15
  • Yeah maybe this is a better way to do it in the long run, i.e. when you have an artist handling those images. For now I just wanted to be able to tweak the look easily with code instead of having to deal with images and a paint program. – initlaunch Dec 18 '10 at 20:19
0

I ended up using UITableViewDelegate's method:

- (void)tableView:(UITableView *)tableView
  willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath;

In it, I check whether the gradient layer has already been added, and if not, I add it.
Not totally happy with it, but it allowed me to move on.

initlaunch
  • 467
  • 5
  • 15