今日はUITableView(UITableViewControllerでも同じだけど)を使ってデータを一覧表示させたときに、 「次を表示...」というセルを用意してページングを行う方法をφ(..)メモメモ
UITableViewに表示させるデータ(dataSource)は、
NSMutableArray *datasに保持しているものとします。
まずページング用のセルを表示するための準備。
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// データ件数
int count = [datas count];
// 初期
if (count==0) {
return 0;
// _offsetCountは現在の画面に表示中のデータ件数
// 「次を表示」を出すためにcount+1件だけセル数を返すようにする
} else if (count==_offsetCount) {
return count+1;
}
// 通常はデータ件数を返す
return count;
}
これで、保持しているデータ+1件目に「次を表示」のセルを出す事ができます。次に実際にセルを作ります。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// まずデータを持った通常のセル
if (indexPath.row!=[datas count]) {
// Cell再利用のためのIdentifier
static NSString *CellIdentifier = @"NormalCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseidentifier:CellIdentifier] autorelease];
}
// 処理の必要があれば処理を書く
return cell;
// ページング用「次を表示」のセル(index.row==[datas count])
} else {
static NSString *CellIdentifier = @"NextCell";
UITableViewCell *nextcell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (nextcell==nil) {
nextcell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
nextcell.textLabel.text = @"次を表示";
return nextcell;
}
}
最後にタップされたときに次のデータを読み込ませます。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// 選択状態解除
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// 通常のセルが押された
if (indexPath.row!=_offsetCount) {
// ページ遷移などの処理
XXViewController *viewController = [[XXViewController alloc] initWithNibName:nil bundle:nil];
[self.navigationController pushViewController:viewController animated:YES];
[viewController release];
// 「次を表示」が押された
} else {
// 次を読み込ませるメソッド(サーバと通信するなど)
[self loadNextData];
// UITableViewを更新させる
[tableView reloadData];
}
}
これでざっとページングの完成です!よくある実装として、通常のセルと「次を表示」のセルとでサイズが異なる場合などは少しコツが必要なので、
それはまた今度書きます。
以上でぇぇえぇぇす。