2012-08-09 74 views
0

我有自定义单元格的表格视图。单元格填充了我的数据。 现在我想让用户重新排列行。我已经实现了这些方法,但是在拖拽重新排序单元格时,我可以看到它正在尝试执行但不能移动到任何地方的显示。它像10个像素一样移动,就好像它将重新排列但回到其位置。如何使用自定义单元重新排序行?如何用自定义单元格重新排列UITableView?

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (editingStyle == UITableViewCellEditingStyleDelete) 
    { 
     [self.dataSource removeObjectAtIndex:indexPath.row]; 
     [tableView reloadData]; 
    } 
} 

-(UITableViewCellEditingStyle)tableView:(UITableView*)tableView editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath 
{ 
    if (self.mytableView.editing) 
    { 
      return UITableViewCellEditingStyleDelete; 
    } 
    return UITableViewCellEditingStyleNone; 
} 

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return YES; 
} 

-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return YES; 
} 

-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath 
{ 
    id stringToMove = [self.dataSource objectAtIndex:sourceIndexPath.row]; 

    [self.dataSource removeObjectAtIndex:sourceIndexPath.row]; 

    [self.dataSource insertObject:stringToMove atIndex:destinationIndexPath.row]; 
} 

-(NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath 
{ 
    if (proposedDestinationIndexPath.section != sourceIndexPath.section) 
    { 
      return sourceIndexPath; 
    } 
    return proposedDestinationIndexPath; 
} 
+1

你应该认真对待你的代码缩进! – JustSid 2012-08-09 07:17:02

+0

xcode的代码缩进很好,只要在这里复制,它就搞砸了。所以任何想法为什么重新排列domenst发生? – 2012-08-09 08:23:14

回答

1

我知道这是旧的,但我仍然会回答它。这里的问题与您的tableView: targetIndexPathForMoveFromRowAtIndexPath: toProposedIndexPath:方法(您的最后一个方法)

您的逻辑阻止任何移动发生。你的if语句:

if (proposedDestinationIndexPath.section != sourceIndexPath.section) 

是说如果所需位置(用户希望把小区的位置)不是我当前的位置,然后回到我的当前位置(所以不要动细胞)。否则,如果我想要的位置(我想去的新位置)是我当前的位置,然后返回所需的位置(这实际上是我的当前位置)

我希望这是有道理的,所以基本上你是说无论如何,要确保每个细胞总是保持在它的当前位置。为了解决这个问题,要么删除这个方法(这是没有必要,除非有举动,是非法的)或切换你的两个return语句,所以:

-(NSIndexPath *)tableView:(UITableView *)tableView 
targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath 
     toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath { 

    if (proposedDestinationIndexPath.section != sourceIndexPath.section) { 
     return proposedDestinationIndexPath; 
    } 
    return sourceIndexPath; 
} 

事实上,唯一需要的方法,以允许重新排列是:tableView: moveRowAtIndexPath: toIndexPath:。再说一遍,除非你想要其他方法的特定行为,否则你可以保存一些代码并删除大部分代码(特别是在这种情况下,你主要只是实现默认设置)。