【问题标题】:How to get Indexpath of cell in UITableView while clicking on Custom accessory Button?单击自定义附件按钮时如何在 UITableView 中获取单元格的索引路径?
【发布时间】:2011-10-17 05:40:35
【问题描述】:

我有 UITableView。我已经创建了带有附件按钮的自定义单元格。现在通过单击附件按钮,我想创建另一个具有编辑单元格功能的视图。为此,我如何找到该单元格的索引路径?以及如何我要通过那个牢房的山谷吗?

我如何调用以下方法:

 - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath

【问题讨论】:

  • 在那个方法中只有你得到 indexpath
  • 你的按钮是自定义的吗?如果没有,请查看该方法的最后一个参数。它给出了索引路径

标签: iphone objective-c xcode


【解决方案1】:

首先要注意的是,当您在单元格中使用自定义 accessoryView 时,将不会调用 tableView:accessoryButtonTappedForRowWithIndexPath: 委托方法。您必须向要添加为自定义附件的按钮添加一些目标/动作,并自己处理点击动作。您应该添加类似这样的自定义附件,

UIButton *accessory = ...;
[accessory addTarget:self action:@selector(onCustomAccessoryTapped:) forControlEvents:UIControlEventTouchUpInside];
...
cell.accessoryView = accessory;

而在 onCustomAccessoryTapped: 方法中,您必须像这样获取索引路径,

- (void)onCustomAccessoryTapped:(UIButton *)sender {

    UITableViewCell *cell = (UITableViewCell *)sender.superview;
    NSIndexPath *indexPath = [tableView indexPathForCell:cell];

    // Now you can do the following
    [self tableView:tableView accessoryButtonTappedForRowWithIndexPath:indexPath];

    // Or you can do something else here to handle the action
}

【讨论】:

  • 如果在 UITableViewCell 中创建按钮会怎样?
  • 您的意思是“如果在 cellForRowAtIndexPath: 方法中创建按钮会怎样”?
  • 不...我通过子类化 UITableViewCell 来自定义单元格。为此,如果我使用上面的代码,那么它会返回 UITableViewCellContainView !!!
  • 这是我知道的旧帖子,但它对我帮助很大。谢谢 EmptyStack。
  • @EmptyStack 嗨,我可以建议对答案进行编辑:就目前而言,我无法使其工作,并在此处查看以查看相同的答案。问题在于superview现在是一个UITableViewCellScrollView,因此必须提升两个级别才能到达UITableViewCell。例如。 with (UITableViewCell *)sender.superview.superview;
【解决方案2】:

indexPath 作为第二个参数传递给方法。

【讨论】:

    【解决方案3】:

    使用“indexPathForCell”的作品如emptystack所述

    [yourViewController.tableView indexPathForCell: 单元格];

    此外,如果您使用的是 tableview 和 Search View,请确保在您的控制器中使用 searchDisplayController

    NSIndexPath *indexPath;
    NSDictionary *campaignMember;
    if(self.searchDisplayController.isActive) {
            indexPath = [[self.searchDisplayController searchResultsTableView] indexPathForCell: cell];
            campaignMember = [self.filterResults objectAtIndex:indexPath.row];
    } else {
        indexPath = [self.tableView indexPathForCell: cell];
        campaignMember = [self.dataRows objectAtIndex:indexPath.row];
    }
    NSString *id = [campaignMember objectForKey:@"Id"];
    

    在我的例子中,“campaignMember”是一个人对象,我需要获取它的 ID。 “self.dataRows”是一个包含主表数据的数组,其中“self.filterResults”包含基于搜索/过滤条件的所有数据的子集或搜索/过滤结果。

    【讨论】:

      猜你喜欢
      • 2020-01-25
      • 1970-01-01
      • 2012-11-23
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 1970-01-01
      相关资源
      最近更新 更多