UITableViewCell の accessoryAction は iPhone SDK 3.0 で廃止されたので accessoryButtonTappedForRowWithIndexPath を使う
ここ数日、iPhoneアプリを作っていますが、慣れない Objective-C, CoCoa Framework 等にハマリまっくています。中でもなかなか解決できなかたのが、下の図のようにテーブル(UITableView, UITableViewCell)の端にボタンを付け、ボタンを押したら何かを実行するケースでした。
参考にしていた書籍は iPhone SDK 2.2 で書かれていたので、UITableViewCellの設定は
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ・・・・ // Configure the cell. cell.text = [titles objectAtIndex:[indexPath indexAtPosition: 1]]; cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton; cell.accessoryAction = @selector(editButtonTapped:); cell.userInteractionEnabled = YES; cell.target = self; return cell; } // ボタンが押された時にViewを切り換える Callback - (IBAction) editButtonTapped:(id)sender { [self.navigationController pushViewController: nextViewController animated: YES]; }
のように書かれていましたが、UITableViewCellの text, accessoryAction, target は iPhone SDK 3.0では Deprecated(廃止)になっていましたし動作もしませんでした。
ドキュメントには、 accessoryAction は廃止されたので tableView:commitEditingStyle:forRowAtIndexPath: or tableView:accessoryButtonTappedForRowWithIndexPath: for handling taps on cells. と書かれていましたが
このような プロパティーやメッソッドは UITableViewCell にはありません !?
そこで、 Google先生に聞いたのですが日本語の情報は見つかりませんでした。 英語のサイトを見ていたら Humble Coder: iPhone tutorial: UITableView from the ground up, part 3というページが見つかりました。
tableView:accessoryButtonTappedForRowWithIndexPath: はUITableViewDelegateプロトコルのメソッドですから、UITableViewController を継承したクラスに定義すれば良かったのでした!
Objective-C, Cocoa への不慣れ。英語力の無さで解決までに時間がかかってしまいました ^^);
上のコードは こんな風に書けば iPhone SDK 3.0以降で動きます。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ・・・・ // Configure the cell. cell.textLabel.text = [titles objectAtIndex:[indexPath indexAtPosition: 1]]; cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton; cell.userInteractionEnabled = YES; return cell; } // ボタンが押された時にViewを切り換える Callback - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath { [self.navigationController pushViewController: nextViewController animated: YES]; }