1

我有一个看起来像这样的代码片段:

[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[array indexOfObject:[array objectAtIndex:indexPath.row]]] withRowAnimation:UITableViewRowAnimationLeft];
[tableView endUpdates];
[tableView reloadData];

它在用户单击附件时执行。第一部分只是为了提供流畅的动画,并不重要,因为 tableView 会在几毫秒后重新加载,但正如我所说,它是为了提供动画。

它应该将选定对象从其当前 indexPath 移动到同一 indexPath 的数组中的值。

显然,这段代码不起作用,所以我只想知道可以做些什么来修复它?

PS:编译时我也会收到警告。通常的“'arrayWithObject:' 的传递参数 1 使指针从整数而不进行强制转换......”(第 3 行)

结束了这个片段:

[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:[array indexOfObject:[arraySubFarts objectAtIndex:indexPath.row]] inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];

[tableView reloadData];
4

2 回答 2

1

您可以使用NSIndexPath类扩展方法+indexPathForRow:inSection:将行转换为索引路径。更多细节在这里

如果您删除和插入行的唯一目的是引起动画,您是否考虑过该reloadRowsAtIndexPaths:withRowAnimation:方法?

于 2010-04-30T20:41:02.817 回答
1
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[array indexOfObject:[array objectAtIndex:indexPath.row]]] withRowAnimation:UITableViewRowAnimationLeft];

取这条线并将其拆分,您将得到以下信息:

NSObject *obj = [array objectAtIndex:indexPath.row];
int *index = [array indexOfObject:obj];
NSArray *otherArray = [NSArray arrayWithObject:index];
[tableView insertRowsAtIndexPaths:otherArray withRowAnimation:UITableViewRowAnimationLeft];

你可能想要的是:

NSObject *obj = [array objectAtIndex:indexPath.row];
NSIndexPath *index = [NSIndexPath indexPathForRow:[array indexOfObject:obj] inSection:0];
NSArray *otherArray = [NSArray arrayWithObject:index];
[tableView insertRowsAtIndexPaths:otherArray withRowAnimation:UITableViewRowAnimationLeft];

但是你为什么不能这样做呢?

NSArray *otherArray = [NSArray arrayWithObject:indexPath];
[tableView insertRowsAtIndexPaths:otherArray withRowAnimation:UITableViewRowAnimationLeft];

使用索引从数组中获取对象,然后使用对象查找索引似乎是多余的。只需使用索引。


编辑更多代码:

NSNumber *obj = [NSNumber numberWithInt:indexPath.row];
int *index = [array indexOfObject:obj];
NSIndexPath *index = [NSIndexPath indexPathForRow:index inSection:0];
NSArray *otherArray = [NSArray arrayWithObject:index];
[tableView insertRowsAtIndexPaths:otherArray withRowAnimation:UITableViewRowAnimationLeft];
于 2010-04-30T20:50:20.033 回答