CALayer和UITableViewCell难题

时间:2012-04-02 21:25:47

标签: ios animation calayer

我想在UITableViewCells中试验动画,所以我尝试了一些简单的CALayers。我几乎立刻遇到了问题,我觉得我在这里真的很遗憾。这是我的代码。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MyIdentifier = @"MyIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
    }
    NSString* title = [self.array objectAtIndex:indexPath.row];
    cell.textLabel.text = title;

    CALayer* layer = [CALayer layer];
    layer.backgroundColor = [UIColor greenColor].CGColor;
    layer.bounds = CGRectMake(10, 10, 50, 50);
    [cell.contentView.layer addSublayer:layer];

    return cell;
}

上面的代码按预期添加了一个绿色方块。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"did select");
    CALayer* layer = [CALayer layer];
    layer.backgroundColor = [UIColor purpleColor].CGColor;
    layer.bounds = CGRectMake(50, 10, 50, 50);
    UITableViewCell* cell = [self tableView:self.tableView cellForRowAtIndexPath:indexPath];
    [cell.contentView.layer addSublayer:layer];

    CGRect bounds = layer.bounds;
    bounds.size.width = 200;
    layer.bounds = bounds;
}

但是,此代码无法按预期工作。我想要一个紫色的正方形,然后会变成一个更大的矩形。为什么那不起作用?

1 个答案:

答案 0 :(得分:0)

这一行有一个错误:

UITableViewCell* cell = [self tableView:self.tableView cellForRowAtIndexPath:indexPath];

相反,请使用:

UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];

第一个调用你定义的函数并在你调用它时创建一个新的UITableViewCell对象(或者将另一个对象出列,这在这里无关紧要)。正确的行从UITableView检索指定行的单元格,这就是你想要的。

另外1)在你写的时候不要指望一个“紫色正方形会变成一个更大的矩形”,因为你需要一些CAAnimation魔法才能达到这个目的。 2)注意.bounds属性,因为图层的协调系统不同,请阅读:http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreAnimation_guide/Articles/Layers.html