2014-07-04 96 views
0

我有一個約15個項目的UITableView。我想長時間按一個單元格來查看複製菜單項以複製單元格的內容,並將其插入複製單元格的正下方。這是我的代碼;複製UITableViewCells錯誤

- (void)tableView:(UITableView*)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath*)indexPath withSender:(id)sender 
{ 
    // Insert the copied item below the item where it was copied from 
    if (action == @selector(copy:)) { 
     UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath]; 
     self.copiedColor = cell.textLabel.text; 

     [self.colors addObject:self.copiedColor]; 
     NSIndexPath *path = [NSIndexPath indexPathForRow:indexPath.row inSection:0]; 

     [self.tableView beginUpdates]; 
     [tableView insertRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationBottom]; 
     [self.tableView endUpdates]; 
    } 
} 

- (BOOL)tableView:(UITableView*)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath*)indexPath withSender:(id)sender 
{ 
    // Show the copy menu item for cells 
    if (action == @selector(copy:)) { 
     return YES; 
    } 

    return NO; 
} 

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

出現複印菜單,我可以複製沒有問題的內容。問題在於插入部分。它實際上插入了單元格,但內容有時會混亂。例如在這裏,我正在複製Crimson的顏色。它被複制並且新單元出現在原始單元下。但請注意,另一個Crimson細胞顯示爲最後一行!

enter image description here enter image description here

如果我複製,而不是它獲得的複製顏色米色,水族被複制,但不會出現任何的它。這是另一個混​​亂!

enter image description here enter image description here

誰能告訴我如何糾正呢?

如果通過我發佈的代碼和圖片難以理解它,我上傳了可運行測試的xcode項目here來演示此問題。請看一看。

感謝提前一噸。

回答

1

我覺得這行:

[self.colors addObject:self.copiedColor]; 

應該是:

[self.colors insertObject: self.copiedColor atIndex: [indexPath row]]; 

否則你堅持你的顏色數組的末尾添加對象,但在表視圖中,在不同的插入它們索引,這樣數據源和表格視圖就會以某種方式失去同步。

而且這條線:

[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath]; 

您可以更改簡單:

[tableView dequeueReusableCellWithIdentifier:@"cell"]; 

對於你所得到的其他奇怪的行爲。另外,在你的案例中檢查cell是否爲nil沒有必要,因爲你已經在故事板中聲明瞭單元格的原型,並且該方法不會返回nil

+0

你試過這個嗎? – F1ank3r

+0

嗨!感謝您的迴應。是的,我做到了。它確實解決了項目增加到最終問題。但還有另一個問題。給我一點時間。我會更新你。 – Isuru

+0

這是新的問題。假設我先複製[Red](http://i.imgur.com/dkeePkL.png)。然後[橙](http://i.imgur.com/DjqjUWi.png)。接下來我複製了紅色和橙色之間的[Blue](http://i.imgur.com/aFlug0P.png)。到目前爲止,一切都很好。假設我複製了第二個[Red](http://i.imgur.com/Gyan05p.png)行,它又被搞砸了。第二個藍色的行不見了,有3個橙色的行!對不起,如果這太令你困惑。如果你下載了我的測試項目,你也可以更容易地重現它。任何想法是什麼造成這個? – Isuru