UIViewにUITableViewを貼付ける | 渋谷で働くUnity野郎

渋谷で働くUnity野郎

備忘録として有効活用していきます。

UIViewにUITableViewを貼付けてみましょう。

イメージとしてはこんな感じです。
$Iichinのブログ
下のボタンは気にしないで下さい(笑)
(※下記にテーブルの実装コードでセクションやセルの内容の例を書いていますが、上記の内容と少し違います)



まずヘッダファイル(.hファイル)でデリゲートの設定をします。

@interface ViewController : UIViewController {
UITableView *table;
}

@property (nonatomic, retain) UITableView *_table;

オレンジの部分を自分のヘッダファイルに追加しましょう。






次に.mファイルの冒頭で@synthesizeします。
(ARCが有効の場合はsynthesizeの必要ありません。)
(また、propertyの宣言もtableで良いでしょう。)
@synthesize _table = table;


さて、これから使用するTableViewを宣言します。

ViewDidLoadなどの、Viewが読み込まれる際に一番最初に呼ばれる関数で、

table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 360, 300) style:UITableViewStylePlain];
table.delegate = self;
table.dataSource = self;
[self.view addSubview:table];

これでBuildするとテーブルビューが表示されます。


あとは、このテーブルビューにセクション数や、セル数、セルの内容、セルが選択された時の挙動を決定するメソッドを導入すれば終わりです。

具体的には、

//セクション数を決める
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 2;
}

//セクションのタイトルを決定する。
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
if(section == 0){
return @"hoge1";
}else{
return @"hoge2";
}

//セクション毎のセルの数を決定する。
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if(section == 0){
return 1;
}else{
return 2;
}
}

//セルの内容を記述
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

if(indexPath.section == 0){
cell.textLabel.text = @"aiueo";
}else{
if(indexPath.row == 0){
cell.textLabel.text = @"kakikukeko";
}else{
cell.textLabel.text = @"sasisuseso";
}

return cell;
}

//セルが選択された時の挙動を決定する。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.section == 0){
NSLog(@"section = 0");
}else{
if(indexPath.row == 0){
NSLog(@"section = 1, row = 0");
}else{
NSLog(@"section = 1, row = 1");
}
}

編集してテーブルのセルを削除する場合は、
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle) editingStyle forRowAtIndexPath:(NSIndexPath *) indexPath
というメソッドが用意されていますが、割愛します。




またコラムとして、テーブルビューの再読み込み、再描画は[table reloadData];でOKです。

何かバグがあれば報告して頂ければ幸いです。