多くのアプリで見かける一覧画面で下に引っ張ると更新する機能を実装してみる。
iOS 6 から追加された UIRefreshControl を使って簡単にできた。
UITableViewController のviewDidLoadメソッド内で UIRefreshControl の初期化処理を行う。
- (void)viewDidLoad { [super viewDidLoad]; UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init]; [refreshControl addTarget:self action:@selector(dataRefresh:) forControlEvents:UIControlEventValueChanged]; self.refreshControl = refreshControl; }
UIRefreshControl インスタンスを作成、addTarget:action:forControlEvents:メソッドでターゲットアクションを設定し、UITableViewController のrefreshControlプロパティに設定する。
そしてアクションに設定したdataRefresh:メソッドを実装してデータの再取得、tableView の更新を行う。
- (void)dataRefresh:(UIRefreshControl *)sender { // 更新処理をここに記述 // 更新終了 [self.refreshControl endRefreshing]; }
ローディングアニメーションはfinishRefreshメソッドを呼んで自分で終了させないと止まらない。
引っ張ったとき以外にも
beginRefreshingメソッドを呼べばローディングアニメーションを開始できる。
UIRefreshControl をカスタマイズ
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
// タイトルを指定する
refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"引っ張って更新"];
// 背景色
refreshControl.backgroundColor = [UIColor lightGrayColor];
// インジケーターの色
refreshControl.tintColor = [UIColor redColor];