UITableViewをアップデートする方法

UITableViewの表示を変更するときは、cellをリロードする必要がある。

それには2つの方法があるので簡単にまとめ。

1. [tableView reloadData]
     //Do some changes
     [tableView reloadData];

reloadDataメソッドは、cellをメソッドが呼ばれた時点で完全にリロードする。
そのため、アニメーションをかけたいときなどは使えない。

用途としては、別のコントローラーでデータを変更して、戻ってきたときに呼んでやると良い。


2. [tableView beginUpdate] ~ [tableView endUpdate]
     [tableView beginUpdate];
     //Do some changes
     [tableView endUpdate];

こちらの場合、beginUpdateからendUpdateの間に記述された処理を、UIVIewのアニメーションを使って実現される*1
その際、自分でanimationメソッドを呼ぶ必要がなく、内部で勝手に作ってくれる。



例えばこのような実装。
UICostomTableViewCellにてisOpenedプロパティを定義しておく。
cellがselectされたときに、!isOpenedだったら、cellの高さを2倍にする。そうでなければデフォルトの高さに戻す。

didSelectRowAtIndexPath:では、開かれたcellのindexPathをopenedCellPathsに格納しおき、heightForRowAtIndexPath:の内部で、格納されているindexPathに対応するcellの高さを2倍にして返している。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    [tableView beginUpdates];     //Update 開始

    UICostomTableViewCell *cell = (UICostomTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
    if(!cell.isOpened)
    {
        //open
        cell.isOpened = YES;        

        //add indexPath
        [_openedCellPaths addObject:indexPath];
    }
    else
    {
        //close
        cell.isOpened = NO;    

        //remove indexPath
        for (NSIndexPath *path in [_openedCellPaths reverseObjectEnumerator])
        {
            if([path compare:indexPath] == NSOrderedSame)
            {
                NSUInteger removeIndex = [_openedCellPaths indexOfObject:path];
                [_openedCellPaths removeObjectAtIndex:removeIndex];
            }
        }
    }
    [tableView endUpdates];     //Update 終了
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat cellHeight = 0.0;
    CGFloat defaultCellHeight = 88;
    for (NSIndexPath *path in_openedCellPaths)
    {
        if([path compare:indexPath] == NSOrderedSame)
        {
            cellHeight = defaultCellHeight * 2;
            return cellHeight;
        }
    }
    cellHeight = defaultCellHeight;     
    return cellHeight;
}

UIViewのアニメーションを実装した訳ではないが、アニメーション付きで実行される。

*1:アニメーションの速度は0.3sです。