将参数传递给选择器

时间:2012-09-06 09:59:23

标签: iphone objective-c ios cocoa-touch ipad

我的自定义单元格中有一个UIButton,我想在用户按下该按钮时触发一个动作但是我需要知道按下UIButton的哪一行。

这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    [self configureCell:cell atIndexPath:indexPath];
    return cell;

    ...

    [button addTarget:self action:@selector(buttonPressedAction:)forControlEvents:UIControlEventTouchUpInside];

}

- (void)buttonPressedAction:(UIButton *)button
{
    //int row = indexPath.row;
    //NSLog(@"ROW: %i",row);
}

如何将indexPath作为参数传递给我的选择器?

4 个答案:

答案 0 :(得分:6)

您可以将按钮的tag属性设置为行号:

button.tag = indexPath.row;

并使用

检索它
NSInteger row = button.tag;

或将索引路径对象本身设置为按钮的关联对象:

objc_setAssociatedObject(button, "IndexPath", indexPath);

NSIndexPath *ip = objc_getAssociatedObject(button, "IndexPath");

答案 1 :(得分:2)

在自定义单元格上添加按钮时,您可以将UIButton的tag属性添加为

UIButton *sampleButton = [[UIButton alloc] init];
sampleButton.tag = indexPath.row;

然后当你打电话时,你可以查看标签

- (void)buttonPressedAction:(UIButton*)sender
{
    if(sender.tag==0)
    {
      //perform action
    }
}
希望它有所帮助。快乐的编码:)

答案 2 :(得分:1)

简单设置按钮标签..

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    [self configureCell:cell atIndexPath:indexPath];
    return cell;

    ...

    [button setTag = indexPath.row]; // Set button tag

    [button addTarget:self action:@selector(buttonPressedAction:)
                                            forControlEvents:UIControlEventTouchUpInside];
    }

    - (void)buttonPressedAction:(id)sender
    {
        UIButton *button = (UIButton *)sender;
        int row = [button superview].tag;
    }
}

答案 3 :(得分:1)

它比设置标签更简单。试试这个..

要获取indexPath,请尝试以下代码。

UIView *contentView = (UIVIew *)[button superview];
UITableViewCell *cell = (UITableViewCell *)[contentView superview];
NSIndexPath *indexPath = [self.tableview indexPathForCell:cell];

OR

NSIndexPath *indexPath = [self.tableview indexPathForCell:(UITableViewCell *)[(UIVIew *)[button superview] superview]];