【问题标题】:Pass an argument to selector将参数传递给选择器
【发布时间】:2012-08-31 02:55:14
【问题描述】:

我的自定义单元格中有一个 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 作为参数传递给我的选择器?

【问题讨论】:

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


【解决方案1】:

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

button.tag = indexPath.row;

并使用检索它

NSInteger row = button.tag;

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

objc_setAssociatedObject(button, "IndexPath", indexPath);

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

【讨论】:

  • 谢谢!按钮的关联对象看起来像一个优雅的解决方案
  • @Prince 与我在示例中所写的完全一样。
  • 它给出警告隐式声明'objc_setAssociatedObject'。由于我需要忽略警告,我正在使用 xcode 4.4.1
  • 已通过#import 解决。谢谢@H2CO3 精彩回答
  • 如果我可以使用该方法将 nsobject 例如 naaarray 或自定义对象作为 People 传递?
【解决方案2】:

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

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

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

- (void)buttonPressedAction:(UIButton*)sender
{
    if(sender.tag==0)
    {
      //perform action
    }
}

希望对您有所帮助。快乐编码:)

【讨论】:

  • 您必须将按钮声明为 UIButton,否则属性访问器将不起作用。 (顺便说一句,我没有 -1)。
【解决方案3】:

比设置标签还要简单。试试这个..

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

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

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

【讨论】:

    【解决方案4】:

    简单设置按钮标签..

    - (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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-06
      • 1970-01-01
      • 2017-09-01
      • 2022-01-18
      • 1970-01-01
      • 2011-04-22
      相关资源
      最近更新 更多