rakuishi.com

[iOS SDK] Tweetbot の設定画面みたいに、アニメーション付きでテーブルビューのデータを表示させる

Tweetbot という Twitter アプリの設定画面で、テーブルビューのデータが下からしゃきんと表示されるのが恰好良かったので、それに似た動きをするサンプルコードを書いてみました。

Tweetbot ― 個性派Twitterクライアント (for iPhone) 2.6.2(¥250)Tweetbot ― 個性派Twitterクライアント (for iPhone) 2.6.2(¥250)

Tweetbot 設定画面ライクなアニメーション付きで UITableView のデータを表示させる

新規プロジェクト Single View Application で作成したものをテンプレートにコードを書いていきます。

ViewController.h

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>

@end

ViewController.m

#import "ViewController.h"

@implementation ViewController {

    UITableView *_tableView;
    NSMutableArray *_objects;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    _tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.backgroundView = nil;
    _tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_tableView];

    _objects = [[NSMutableArray alloc] init];

    [self performSelector:@selector(setObjects) withObject:nil afterDelay:1.f];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - TableView animation

- (void)setObjects
{
    for (int i=0; i<100; i++) {
        [_objects addObject:[NSString stringWithFormat:@"%d", i+1]];
    }
    [_tableView reloadData];

    CATransition *animation = [CATransition animation];
    [animation setType:kCATransitionPush];
    [animation setSubtype:kCATransitionFromTop];
    [animation setDuration:0.2f];
    [[_tableView layer] addAnimation:animation forKey:@"ReloadAnimationKey"];
}

#pragma mark - TableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _objects.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    cell.textLabel.text = [NSString stringWithFormat:@"%@", [_objects objectAtIndex:indexPath.row]];

    return cell;
}

@end

CATransition で切替効果を演出しています。Tweetbot ライクな動きをするのに重要なのはこの 2 行です。プッシュで表示+上方向で、切り替えるようにしています。

    [animation setType:kCATransitionPush];
    [animation setSubtype:kCATransitionFromTop];

実行すると下図みたいに、下から上に向かってテーブルビューのデータが表示されます。格好いいですね!