从UITableViewCell中的UIBarButtonItem获取索引路径

时间:2013-08-06 06:39:18

标签: ios uitableview uibarbuttonitem

我有UITableViewController这样的人。在每行的accessoryView中带有UIBarButtonItem的分组表视图。

enter image description here

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

现在我在点击相应的UITableViewCell时尝试获取UIBarButtonItem的索引路径。 (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。任何人都可以告诉我它有什么问题以及如何纠正这个问题?我真的很感激。

谢谢。

5 个答案:

答案 0 :(得分:3)

尝试使用view.superview.superview;代替view.superview;

答案 1 :(得分:2)

你这样设置loginutton标签

loginButton.tag=indexPath.section;

在点击事件中获取indexpath

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

答案 2 :(得分:1)

cellForRowAtIndexPath

[loginButton setTag:indexPath.section];

登录:

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

答案 3 :(得分:1)

CellForRow: -

loginButton.tag=indexPath.row;

登录操作方法: -

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

答案 4 :(得分:-1)

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

UITableViewCell *cell= [tableView cellForRowAtIndexPath:indexPath];