在TableView中移动单元格

时间:2013-04-14 18:18:39

标签: ios objective-c uitableview

我有一个表格视图,用户可以按照他希望的顺序移动和重新排列单元格。但是当他多次移动/重新排列细胞时,持有物品的阵列会因为物品的顺序而完全混乱,但在视觉上一切都很好。我究竟做错了什么?提前谢谢你......

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{

    id object1 = [_items5 objectAtIndex:sourceIndexPath.row];
    id object2 = [_items5 objectAtIndex:destinationIndexPath.row];

    [_items5 replaceObjectAtIndex:sourceIndexPath.row withObject:object2];
    [_items5 replaceObjectAtIndex:destinationIndexPath.row withObject:object1];

其中_items5是NSMutableArray并在viewDidLoad中初始化

1 个答案:

答案 0 :(得分:1)

您正在交换两个项目,而不是移动一个已移动的项目。你想要:

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    id object = [_items5 objectAtIndex:sourceIndexPath.row];
    [_items5 removeObjectAtIndex:sourceIndexPath.row];
    [_items5 insertObject:object atIndex:destinationIndexPath.row];
}

注意:如果使用MRC,您需要保留object,以便在将其放回阵列之前不会取消分配。

相关问题