サンプルのソースコードはこちら。
以下解説です。
まずはテーブルの基本部分から。UITableViewControllerのサブクラス、またはUITableViewDataSourceデリゲート実装クラスのコードには最低限次のメソッドを実装する必要があります。
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 5;
}
- (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] autorelease];
}
// Configure the cell.
cell.textLabel.text = @"test";
return cell;
}
上記のコードに、次のコードを加えると、Deleteボタンが表示されるようになります。
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
}
ここで、
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleInsert;
}
をさらに加えると、Deleteボタンは表示されなくなります。このメソッドでは、セルごとのUITableViewCellEditingStyleを決めています。
UITableViewCellEditingStyleDelete...
UITableViewCellEditingStyleInsert...
このメソッドを実装しない場合、デフォルトではUITableViewCellEditingStyleDeleteとして振る舞うようです(UITableViewCell.hを見ると、実際にはデフォルト値はUITableViewCellEditingStyleNoneになっているようですが)。
ということで、フリックして表示される Delete ボタンと、 セルの左に表示されるプラスボタン( UITableViewCellEditingStyleInsert のスタイル)は、通常は同時利用できません。
ただ、次のような工夫をすることで、同じセル上で Delete ボタンとプラスボタンを表示させることができます。
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return self.isEditing ? UITableViewCellEditingStyleInsert : UITableViewCellEditingStyleDelete;
}
このコードにより、通常時はフリックでDeleteボタンが表示され、ナビゲーションバー右端のEditボタンタップ時にはプラスボタンが表示されるようになります。

0 件のコメント:
コメントを投稿