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

标签 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];   
}

但是,当我在模拟器中单击一个单元格时,控制台调试消息是:“事件已触发(空)”,我的应用程序很快就崩溃了。

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

最佳答案

首先,index 是一个int,因此您的 NSLog 需要如下所示(注意 %d):

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

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

关于iphone - UITableView Cell - 从按钮获取 IndexPath.row?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3482029/

相关文章:

iphone - 解码字符串时获取垃圾和特殊字符

iphone - map 上的重叠注释 (MKAnnotationView) 问题

iOS Swift 如何创建协议(protocol)实例

ios - Swift – 关闭 View Controller 后 TableView 数据未重新加载

ios - 在 iOS 中对 pdf 文档进行数字签名

iphone - ios uiscrollview 与 uiimageviews 之间启用分页如何检测哪个在屏幕上/可见

iphone - 如何正确清空 NSMutableArray

objective-c - 在 tvOS 下有条件编译的最佳方法是什么

swift - TableView 中的单元格不显示信息。 swift

iphone - UITableViewCells出现在backgroundView后面