I wanted to experiment with animations in UITableViewCells so I tried some simple stuff with CALayers. I almost immediately ran into problems, and I feel I am really missing something here. Here is my code.
- (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;
}
The above code adds a green square as expected.
- (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;
}
This code however, did not work as expected. I wanted a purple square, which would then grow to a larger rectangle. Why did that not work?
There is a mistake at this line:
UITableViewCell* cell = [self tableView:self.tableView cellForRowAtIndexPath:indexPath];
instead, use this:
UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
The first one calls your defined function and creates a new UITableViewCell object when you call it (or dequeues another one, which doesn't matter here). The correct line retrieves the cell at the specified row from the UITableView, which is what you want.
Also 1) don't expect a "purple square, which would then grow to a larger rectangle" as you write, because you will need some CAAnimation magic to achieve this. 2) be careful about the .bounds property, because layer's coordination system is different, read this: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreAnimation_guide/Articles/Layers.html