1

我有一个 UITableView 正在为用户处理核心数据 o 添加他们自己的单元格......但我希望他们能够按照他们想要的方式重新排序 TableViewCells......我现在使用代码但是每当重新排序时,假设我去添加另一个单元格,它将返回常规状态...如果您迷路了,请看下面的图片...

下面是代码:

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
   if (indexPath.row == 0) // Don't move the first row
       return NO;

   return YES;
}

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

 id ob = [_devices objectAtIndex:destinationIndexPath.row];

        [_devices replaceObjectAtIndex:destinationIndexPath.row withObject:[_devices objectAtIndex:sourceIndexPath.row]];
        [_devices replaceObjectAtIndex:sourceIndexPath.row withObject:ob];
}

重新订购前

在重新订购期间

添加新单元格

添加新单元格后(返回日期排序)

4

1 回答 1

2

您应该在您的实体上添加一个 order 属性,以便您的排序顺序是持久的。

然后您的表视图的数据源需要按该顺序键排序。

您的数组很可能_devices正在使用您的核心数据获取请求的结果重新初始化,因此您对订单的修改会丢失。

更新评论

假设您有一个名为的实体,它是具有名为的属性Device的子类,您可以执行以下操作。NSManagedObjectorder

NSSortDescriptor *orderSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"order" ascending:YES];
[devicesFetchRequest setSortDescriptors:@[orderSortDescriptor]];

然后,当您执行获取请求并在_devices数组中捕获结果时,它们将按 order 属性排序。

然后,- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath您将需要更新受影响实体的 order 属性。

如果您将设备从位置 5 移动到位置 2,那么您需要将位置 2-4 的实体更新 +1,并将移动的实体更新为 2。这对于大型数据集可能会很快变得低效,但对于小型数据集,它应该执行美好的。

于 2013-04-24T22:02:41.217 回答