スキップしてメイン コンテンツに移動

UITableViewのセクションについて

UITableView セクションの設定


■適当にデータを用意する

// セクション名
keys = [[NSArray alloc] initWithObjects:@"0", @"1", @"2", nil];

// 各セクションに入れるデータを作成
NSArray *section1 = [NSArray arrayWithObject:@"A", @"B", @"C", nil];
NSArray *section2 = [NSArray arrayWithObject:@"D", @"E", @"F", nil];
NSArray *section3 = [NSArray arrayWithObject:@"G", @"H", @"I", nil];

NSArray *sections = [NSArray arrayWithObject:section1, section2, section3, nil];

// セクション名とデータを合わせ込む
dataSource = [[NSDictionary alloc] initWithObjects:sections forKeys:keys];



■セクション名、セクション数、セクションに含まれる行を返すようにする

// セクション名を返す
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [key objectAtIndex:section];
}

// テーブルに含まれるセクションの数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [keys count];
}

// セクションに含まれる行の数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

id key = [keys objectAtIndex:section];
return [[dataSource objectForKey:key] count];
}


■上手いこと行データを生成する

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *identifier = @"identifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

// セクションを名をまず抽出
id key = [key objectAtIndex:indexPath.section];

// セクション名のセクションにあるrow番目のデータを取り出す
NSString *text = [[dataSource objectForKey:key] objectAtIndex:indexPath.row];
cell.textLabel.text = text;

return cell;
}

コメント

このブログの人気の投稿

日本に来た 今三週間

四月六日に日本に来た、今三週間になった。 嬉しくなかった、悲しくなかった。 日本の携帯電話のカメラはとてもいいよ、私は今撮影が好きだ、いつも寮に帰る途中で花とか魚とか写真を撮る。これも生活の趣味だ。 滴は綺麗だ 桜が凋んで落ちる 天気がいいとき、自転車に乗って、食材を買った。 自分で料理をつくる、おいしそうでしょう。 昨日清水寺に行った、天気はとても熱いね。日に焼けすぎたので、腕は今赤い。 側に花があるので、赤い清水寺はもっと美しそうだ。 木の色は艶やかだ。