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

uni*_*der 6 iphone objective-c selector uibutton uitableview

我目前在单元格中定义了一个按钮,以及跟踪其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];   
}
Run Code Online (Sandbox Code Playgroud)

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

如何正确获取我的clickedCallSign方法中的indexPath.row值?

Ben*_*tto 2

首先,index是一个int,所以你的 NSLog 需要看起来像这样(注意%d):

NSLog(@"event triggered %d", index);
Run Code Online (Sandbox Code Playgroud)

(这可能会导致崩溃,但也可能是其他原因导致了不稳定。)