【问题标题】:Get the indexpath from a UIBarButtonItem in a UITableViewCell从 UITableViewCell 中的 UIBarButtonItem 获取 indexpath
【发布时间】:2013-08-06 06:39:17
【问题描述】:

我有一个这样的UITableViewController。在每行的附件视图中带有UIBarButtonItem 的分组表视图。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    UIToolbar *toolBar = [[TransparentToolbar alloc] init];
    UIBarButtonItem *loginButton = [[UIBarButtonItem alloc] initWithTitle:@"Check"
                                                                    style:UIBarButtonItemStyleBordered
                                                                   target:self
                                                                   action:@selector(login:)];
    toolBar.frame = CGRectMake(0, 0, 100, 103);
    toolBar.items = @[loginButton];
    cell.accessoryView = toolBar;

    return cell;
}

现在我试图在单击相应的UIBarButtonItem 时获取UITableViewCell 的索引路径。 (source)

- (void)login:(UIBarButtonItem *)button
{
    UIBarButtonItem *barButton = button;
    UIView *view = [barButton valueForKey:@"view"];
    UITableViewCell *cell = (UITableViewCell *)view.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSLog(@"secton: %d", indexPath.section);
}

但无论我点击哪个栏按钮,它都只返回 0。任何人都可以告诉我它有什么问题以及如何纠正这个问题?我真的很感激。

谢谢。

【问题讨论】:

  • 你可以在tableView cellForRowAtIndexPath的barButton上添加一个tag,然后在login方法中得到tag的值。

标签: ios uitableview uibarbuttonitem


【解决方案1】:

尝试使用view.superview.superview; 而不是view.superview;

【讨论】:

  • 哇!这行得通!这是一种更优雅的方式。您能否解释一下这条线 - view.superview.superview; 在我的情况下是如何工作的?谢谢你的回答顺便说一句。 :)
  • 我现在无法测试它,但我认为 view.superview 在这种情况下是单元格的 accesoryView 。单元格是它的超级视图。
  • 啊,我明白了。再次非常感谢。
【解决方案2】:

你这样设置loginutton标签

loginButton.tag=indexPath.section;

在点击事件中获取索引路径

- (void)login:(UIBarButtonItem *)button
{
UITableViewCell *cell= [tableView cellForRowAtIndexPath:button.tag];
}

【讨论】:

    【解决方案3】:

    cellForRowAtIndexPath:

    [loginButton setTag:indexPath.section];
    

    登录:

       NSLog(@"secton: %d",(long int) [barButton tag]);
    

    【讨论】:

      【解决方案4】:

      CellForRow:--

      loginButton.tag=indexPath.row;
      

      登录操作方法:--

       NSIndexPath *indexPath=[NSIndexPath indexPathForItem:button.tag inSection:0];
      

      【讨论】:

        【解决方案5】:

        为每个单元格中的每个barbutton项设置不同的标签。然后根据按钮标签你可以找到它是哪个单元格。你可以这样访问

        UITableViewCell *cell= [tableView cellForRowAtIndexPath:indexPath];
        

        【讨论】:

          猜你喜欢
          • 2017-07-29
          • 2013-03-20
          • 2014-11-10
          • 1970-01-01
          • 1970-01-01
          • 2012-10-24
          • 2014-09-25
          • 1970-01-01
          • 2014-07-27
          相关资源
          最近更新 更多