2011-11-08 36 views
23

我有一個UITableView和一些UITableViewCells我通過Interface Builder手動創建。我已經爲每個單元分配了一個outlet,並將它們連接到方法CellForRowAtIndexPath中的UITableView。在這種方法中,我使用switch(case)方法使特定的單元格出現在UITableView中,取決於具體情況。檢查一個特定的UITableViewCell是否在UITableView中可見

現在,我想找到一個特定的單元格,並檢查他是否存在於UITableView之內。我使用方法:UITableView.visibleCells獲取表視圖中的單元格數組。我的問題是 - 如何檢查數組中是否存在特定的單元格?我可以使用我分配給它的插座嗎? - (最好的解決方案),或者,我可以使用一個標識符以及如何?

謝謝:)

回答

74

注意,您可以如用indexPathsForVisibleRows這樣:

NSUInteger index = [_people indexOfObject:person]; 
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0]; 
    if ([self.tableView.indexPathsForVisibleRows containsObject:indexPath]) { 
     [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] 
          withRowAnimation:UITableViewRowAnimationFade]; 
    } 

如果你有indexPath(並且不需要實際的細胞)可能是便宜

PS:_peopleNSArray在這種情況下用作我的後端。

+3

在大多數情況下,此解決方案比可接受的解決方案更好。 – Envil

+0

這個作品完美!謝謝:) – Gaurav

11

可以使用的UITableView方法:

[tableView indexPathForCell:aCell]; 

如果電池不在的tableView將返回零存在。否則,您將獲得單元格的NSIndexPath。

+1

那是工作的,謝謝:) – ozking

+4

重用 –

+0

謝謝細胞時,這是不行的,它的工作原理+1 – iLearner

16
if ([tableView.visibleCells containsObject:myCell]) 
{ 
    // Do your thing 
} 

這是假設你有一個包含電池,你有興趣,我覺得你的問題做一個單獨的實例變量,但目前尚不清楚。

+0

謝謝,這是實施Sorig給我的解決方案的另一種方式:) – ozking

+0

這是原始問題的正確答案,如果單元格可見。感謝您提供乾淨簡單的答案。 –

0

爲此,您可以在斯威夫特3,以檢查是否UITableViewCell可見:

let indexPathToVerify = IndexPath(row: 0, section: 0) 
let cell = tableView.cellForRow(at: indexPathToVerify) 

if tableView.visibleCells.contains(cell) { 
    // the cell is visible 
} 
相關問題