小ネタです。
UITableViewDelegate には tableView:accessoryButtonTappedForRowWithIndexPath: というメソッドがあって、UITableViewCell のアクセサリをタップした時に呼ばれる… はずなのですが、accessoryView に適当なUIViewを代入した時に呼ばれなかったのでハマりました。
どうも調べて見ると アクセサリとは accessoryViewを含まないらしく accessoryType (UITableViewCellAccessoryType) のみ、対応しているようです。
こちらのサンプルコード はそのものズバリ、accessoryViewをタップした時の挙動のデモになっています。
実際は特に難しいことをしているわけではなく、単にUIButton をaccessoryViewに入れてイベントを受け取って、tableView:accessoryButtonTappedForRowWithIndexPath:に処理を流しているだけですが。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
/** UITableViewCell の初期化など (略) **/
// accessoryViewに入れるUIButtonの初期化
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = ...;
[button addTarget:self
action:@selector(checkButtonTapped:event:)
forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = button;
return cell;
}
- (void)checkButtonTapped:(id)sender event:(id)event
{
// ボタンがタップされたらtableView:accessoryButtonTappedForRowWithIndexPathに処理を流す
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
if (indexPath != nil)
{
[self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
// UITableViewCell の accessoryTypeにUITableViewCellAccessoryDetailDisclosureButtonなど適当な値が入っている場合はこのメソッドが直接呼ばれる
}




0 comments:
コメントを投稿