2012-04-02 31 views
0

我想在UITableViewCells中嘗試動畫,所以我嘗試了一些簡單的CALayers。我幾乎立即遇到了問題,我覺得我在這裏真的錯過了一些東西。這是我的代碼。CALayer和UITableViewCell難題

- (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; 
} 

但是,此代碼沒有按預期工作。我想要一個紫色的正方形,然後長到一個更大的矩形。爲什麼這不起作用?

回答

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