4

我有一个自定义UITableViewCell,其中添加了两个自定义UIButton。在其中一个按钮上,我希望能够从内部删除单元格行myMethod()

该方法由addTarget:@selector(myMethod:)inside调用cellForRowAtIndexPath

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ...
    cell.acceptButton.tag = indexPath.row;
    [cell.contentView addSubview:acceptButton];

    [cell.acceptButton addTarget:self action:@selector(myMethod:) forControlEvents:UIControlEventTouchUpInside];
}

这有效,实际方法被成功调用。

- (void)myMethod:(id)sender {
   NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; //works fine (correct indexPath is returned)
   friendsArray removeObjectAtIndex:indexPath.row]; //works fine (correct indexPath.row is returned and the object is removed from the array)
   [tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; //throws error below
}

错误:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSArray initWithObjects:count:]: attempt to insert nil object at objects[0]'
*** Call stack at first throw:
(
 0   CoreFoundation                      0x020a9be9 __exceptionPreprocess + 185
 1   libobjc.A.dylib                     0x021fe5c2 objc_exception_throw + 47
 2   CoreFoundation                      0x01ff3ffe -[__NSPlaceholderArray initWithObjects:count:] + 494
 3   CoreFoundation                      0x020158a3 +[NSArray arrayWithObject:] + 67
 4   MyApp                          0x00071d1b -[FriendListViewController myMethod:] + 417
 5   MyApp                          0x00020b87 -[MBProgressHUD launchExecution] + 151
 6   Foundation                          0x004a3d4c -[NSThread main] + 81
 7   Foundation                          0x004a3cd8 __NSThread__main__ + 1387
 8   libSystem.B.dylib                   0x9461f85d _pthread_start + 345
 9   libSystem.B.dylib                   0x9461f6e2 thread_start + 34

通常我会在删除单元格中的一行时这样做。这工作正常:

- (void)tableView:(UITableView *)tableview commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if(editingStyle == UITableViewCellEditingStyleDelete) {
  //Delete the object from the friends array and the table.
  [friendsArray removeObjectAtIndex:indexPath.row];
  [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }
}
4

2 回答 2

0

如果您在每个单元格或多个单元格上使用 uibutton 并设置相同的选择器,那么找出单元格的最佳选项是使用标签。

当我想将附件按钮的颜色更改为绿色时,我这样做了(我不知道苹果是否允许这样做,但只是我想尝试的东西)。所以制作了一个自定义按钮并将其背景图像更改为绿色,然后在附件视图中我添加了该按钮。它工作得很好。您需要在tableView:cellForRowAtIndexPath:方法中设置标签

于 2011-01-12T06:45:35.650 回答
0

问题在于数组初始化,而不是行删除。尝试再次调试此方法并检查 indexPath 是否可以为 nil。

于 2011-01-12T06:52:19.157 回答