2010-04-30 56 views
1

我有一段代碼,看起來像這樣:獲取tableview的insertRowsAtIndexPaths來接受indexOfObject?

[tableView beginUpdates]; 
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft]; 
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[array indexOfObject:[array objectAtIndex:indexPath.row]]] withRowAnimation:UITableViewRowAnimationLeft]; 
[tableView endUpdates]; 
[tableView reloadData]; 

當用戶點擊附件它得到執行。第一部分只是爲了提供一個流暢的動畫,並不重要,因爲tableView在幾毫秒後重新加載,但正如我所說的,它提供了一個動畫。

它應該將所選對象從其當前indexPath移動到同一indexPath處的數組中的值。

顯然,這段代碼不起作用,所以我只想知道可以做些什麼來修復它? PS:我也在編譯時得到一個警告。通常的「傳遞的參數1‘arrayWithObject:’時將整數指針不進行強制轉換......」(3號線)

結束了這個片段:

[tableView beginUpdates]; 
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft]; 
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:[array indexOfObject:[arraySubFarts objectAtIndex:indexPath.row]] inSection:0]] withRowAnimation:UITableViewRowAnimationFade]; 
[tableView endUpdates]; 

[tableView reloadData]; 

回答

1

可以使用NSIndexPath類擴展方法+indexPathForRow:inSection:將行轉換爲索引路徑。更多詳情here

如果您唯一的意圖是刪除並插入該行將導致動畫,您是否考慮過reloadRowsAtIndexPaths:withRowAnimation:方法?

1
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[array indexOfObject:[array objectAtIndex:indexPath.row]]] withRowAnimation:UITableViewRowAnimationLeft]; 

以這條線和分裂它你會得到如下:

NSObject *obj = [array objectAtIndex:indexPath.row]; 
int *index = [array indexOfObject:obj]; 
NSArray *otherArray = [NSArray arrayWithObject:index]; 
[tableView insertRowsAtIndexPaths:otherArray withRowAnimation:UITableViewRowAnimationLeft]; 

你可能想要的是:

NSObject *obj = [array objectAtIndex:indexPath.row]; 
NSIndexPath *index = [NSIndexPath indexPathForRow:[array indexOfObject:obj] inSection:0]; 
NSArray *otherArray = [NSArray arrayWithObject:index]; 
[tableView insertRowsAtIndexPaths:otherArray withRowAnimation:UITableViewRowAnimationLeft]; 

但是你爲什麼不能這樣做呢?

NSArray *otherArray = [NSArray arrayWithObject:indexPath]; 
[tableView insertRowsAtIndexPaths:otherArray withRowAnimation:UITableViewRowAnimationLeft]; 

使用索引從數組中獲取對象然後使用該對象來查找索引似乎是多餘的。只需使用索引。


編輯與更多的代碼:

NSNumber *obj = [NSNumber numberWithInt:indexPath.row]; 
int *index = [array indexOfObject:obj]; 
NSIndexPath *index = [NSIndexPath indexPathForRow:index inSection:0]; 
NSArray *otherArray = [NSArray arrayWithObject:index]; 
[tableView insertRowsAtIndexPaths:otherArray withRowAnimation:UITableViewRowAnimationLeft]; 
+1

爲什麼我這樣做的原因是因爲新的指數是在一個陣列的當前indexPath。 (如果indexPath爲2,則數組中的值2可能爲20)。 – Emil 2010-04-30 20:58:09

+0

啊,好吧。你發佈的代碼是在索引2處抓取對象,在索引2處查找對象的索引,並用該對象創建一個數組。我在上面添加了更多的代碼,可能會更接近您的需求。 – MrHen 2010-04-30 21:11:41

+0

看到更新後的第一篇文章,我修好了:) – Emil 2010-05-01 07:49:49