将参数传递给选择器

Pup*_*lam 3 iphone cocoa-touch objective-c ipad ios

我在自定义单元格中有一个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);
}
Run Code Online (Sandbox Code Playgroud)

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

小智 6

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

button.tag = indexPath.row;
Run Code Online (Sandbox Code Playgroud)

并使用.检索它

NSInteger row = button.tag;
Run Code Online (Sandbox Code Playgroud)

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

objc_setAssociatedObject(button, "IndexPath", indexPath);
Run Code Online (Sandbox Code Playgroud)

NSIndexPath *ip = objc_getAssociatedObject(button, "IndexPath");
Run Code Online (Sandbox Code Playgroud)