LoginSignup
35
36

More than 5 years have passed since last update.

UITableViewCell 上に配置した UIControl のアクションから indexPath を取得する

Last updated at Posted at 2013-01-27

UITableViewCell に UIControl を配置し、アクションを MyTableViewController に繋いだとき、アクションが発火された cell の indexPath を知るにはどうすればいいでしょうか?

UIControl に tag を設定することもできますが、row や section が増えると tag も複雑になり、魔窟のようなコードになってしまいます。

UITableViewCell のサブクラスを作成し、cell 内でアクションを受け取って indexPath を取得、デリゲートで通知する手もあります。
しかし、特に Storyboard の Prototype Cells を利用する場合、アクションの行き先はコントローラに纏めたいものです。

そこで、アクションの sender から superview を辿って cell を取得し、UITableView の indexPathForCell: インスタンスメソッドを使って indexPath を取得してみましょう。

MyTableViewController.m
- (IBAction)action:(id)sender {
    UITableViewCell *cell = [self findUITableViewCellFromSuperViewsForView:sender];
    if (cell) {
        NSLog(@"indexPath = %@", [self.tableView indexPathForCell:cell]);
    }
}

- (UITableViewCell *)findUITableViewCellFromSuperViewsForView:(id)view {
    if (![view isKindOfClass:[UIView class]]) {
        return nil;
    }
    UIView *superView = view;
    while (superView) {
        if ([superView isKindOfClass:[UITableViewCell class]]) {
            break;
        }
        superView = [superView superview];
    }
    return (UITableViewCell *)superView;
}

あとは取得した indexPath を使って煮るなり焼くなりしましょう。

参考

UITableView Class Reference
http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableView_Class/Reference/Reference.html

35
36
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
35
36