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;
}
■適当にデータを用意する
// セクション名
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;
}
コメント
コメントを投稿