2012-08-09 59 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:。再說一遍,除非你想要其他方法的特定行爲,否則你可以保存一些代碼並刪除大部分代碼(特別是在這種情況下,你主要只是實現默認設置)。