UITableView Cell - 从按钮获取IndexPath.row?

时间:2010-08-14 04:38:37

标签: iphone objective-c uitableview uibutton selector

我目前在单元格中定义了一个按钮,以及跟踪其UITouchDown操作的方法,如下所示:

- (void) clickedCallSign:(id)sender {

    int index = [sender tag];
    NSLog(@"event triggered %@",index);

}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    //Callsign button
    UIButton *button;

    CGRect rect = CGRectMake(TEXT_OFFSET_X, BORDER_WIDTH, LABEL_WIDTH, LABEL_HEIGHT);
    button = [[UIButton alloc] initWithFrame:rect];
    cell.tag=[indexPath row];
    button.tag=[indexPath row];
    [button addTarget:self action:@selector(clickedCallSign:) forControlEvents:UIControlEventTouchDown];
    [button setBackgroundColor:[UIColor redColor]];
    [button setTitle:@"hello" forState:UIControlStateNormal];
    [cell.contentView addSubview:button];
    [button release];   
}

但是,当我单击模拟器中的单元格时,控制台调试消息为:“event triggered(null)”,我的应用程序很快就崩溃了。

如何正确地将indexPath.row值转换为clickedCallSign方法?

3 个答案:

答案 0 :(得分:2)

首先,indexint,因此您的NSLog需要看起来像这样(请注意%d):

NSLog(@"event triggered %d", index);

(这可能可能导致崩溃,但也可能是其他完全导致不稳定的事情。)

答案 1 :(得分:2)

标记很好,直到你没有两个部分和行。尝试另一种获取索引路径的方法:

- (void)tableView:(UITableView*)tableView willDisplayCell:(UITableViewCell*)cell forRowAtIndexPath:(NSIndexPath*)indexPath {

    //...

    [button addTarget:self action:@selector(clickedCallSign:withEvent:) forControlEvents:UIControlEventTouchDown];

    //...

}

// Get the index path of the cell, where the button was pressed
- (NSIndexPath*)indexPathForEvent:(id)event
{
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    return [self.tableView indexPathForRowAtPoint:currentTouchPosition];
}

- (IBAction)clickedCallSign:(id)sender withEvent:(UIEvent*)event
{
    NSIndexPath* buttonIndexPath = [self indexPathForEvent:event];
}

答案 2 :(得分:2)

如果您不想使用标记字段,请让按钮调用此方法:

- (void)tapAccessoryButton:(UIButton *)sender
{
    UIView *parentView = sender.superview;

    // the loop should take care of any changes in the view heirarchy, whether from
    // changes we make or apple makes.
    while (![parentView.class isSubclassOfClass:UITableViewCell.class])
        parentView = parentView.superview;

    if ([parentView.class isSubclassOfClass:UITableViewCell.class]) {
        UITableViewCell *cell = (UITableViewCell *) parentView;
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        [self tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
    }
}