rakuishi.com

[iOS 6] 引っ張って更新を簡単に実装できる UIRefreshControl を TableView で使ってみる

引っ張って更新が iOS 6 からメールや Passbook で出来るようになりました(写真は Passbook)。

この更新方法が iOS 6 から簡単に実装できるようになったみたいですので、実際に使われる機会が多いテーブルビューに組み込んでみました。

だいたい以下のような感じで、引っ張って更新が出来ます。

ここでは、1 秒後に更新終了を知らせる endRefreshing というメソッドを呼んでいます。実際には、処理や通信が終ったタイミングで呼ぶと、グッドです。

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> {

}

@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController {

    UITableView *_tableView;
    UIRefreshControl *_refreshControl;
}

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

    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0.f, 0.f, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];

    _refreshControl = [[UIRefreshControl alloc] init];
    [_refreshControl addTarget:self action:@selector(refresh) forControlEvents:UIControlEventValueChanged];
    [_tableView addSubview:_refreshControl];
}

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

#pragma mark - TableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%d", indexPath.row];

    return cell;
}

#pragma mark -

- (void)refresh
{
    NSLog(@"refresh");

    [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(endRefresh) userInfo:nil repeats:NO];
}

- (void)endRefresh
{
    [_refreshControl endRefreshing];
}

@end

シミュレータで動かしてみるとこんな感じ。

参考:iOS 6 で追加された UIRefreshControl の使い方 | a.out