开发者

UITableViewCell gradient layer auto resize

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 he开发者_开发百科ight (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;
}


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;


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜