24/7 twenty-four seven

iOS/OS X application programing topics.

UITableView で メール.app のような複数選択を実現する Undocumented API

UITableView の複数セルの選択は、実は Undocumented API として存在しています。
実装してもそれほど手間ではありませんし、審査に通るかどうかも不明なので、今のところ使いどころはないかもしれませんが、紹介します。


UITableViewDelegate に設定したクラスに tableView:tableView editingStyleForRowAtIndexPath: メソッドを実装し、UITableViewCellEditingStyle に 3 を返します。

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 3;
}

このデリゲートメソッド自体は公開されているメソッドです。
UITableViewCellEditingStyle が下記のように定義されており、定数で定義されていない値を直接数値を指定して返していることになります。

typedef enum {
   UITableViewCellEditingStyleNone,
   UITableViewCellEditingStyleDelete,
   UITableViewCellEditingStyleInsert
} UITableViewCellEditingStyle;


選択されたセルのインデックスパスは indexPathsForSelectedRows というメソッドで取得できます。このメソッドは非公開です。

- (NSArray *)indexPathsForSelectedRows;


一つ一つのセルの選択、選択解除のタイミングで下記の公開されているデリゲートメソッドが呼び出されるので、非公開のメソッドを使わなくても選択状態を管理することは可能です。

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
- (NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath;
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath;