Determine if a tableview cell is visible
To checking tableview cell is visible or not use this code of line
if(![tableView.indexPathsForVisibleRows containsObject:newIndexPath])
{
// your code
}
here newIndexPath is IndexPath of checking cell.....
Swift 3.0
if !(tableView.indexPathsForVisibleRows?.contains(newIndexPath)) {
// Your code here
}
I use this in Swift 3.0
extension UITableView {
/// Check if cell at the specific section and row is visible
/// - Parameters:
/// - section: an Int reprenseting a UITableView section
/// - row: and Int representing a UITableView row
/// - Returns: True if cell at section and row is visible, False otherwise
func isCellVisible(section:Int, row: Int) -> Bool {
guard let indexes = self.indexPathsForVisibleRows else {
return false
}
return indexes.contains {$0.section == section && $0.row == row }
} }
UITableView
has an instance method called indexPathsForVisibleRows
that will return an NSArray
of NSIndexPath
objects for each row in the table which are currently visible. You could check this method with whatever frequency you need to and check for the proper row. For instance, if tableView
is a reference to your table, the following method would tell you whether or not row 0 is on screen:
-(BOOL)isRowZeroVisible {
NSArray *indexes = [tableView indexPathsForVisibleRows];
for (NSIndexPath *index in indexes) {
if (index.row == 0) {
return YES;
}
}
return NO;
}
Because the UITableView
method returns the NSIndexPath
, you can just as easily extend this to look for sections, or row/section combinations.
This is more useful to you than the visibleCells
method, which returns an array of table cell objects. Table cell objects get recycled, so in large tables they will ultimately have no simple correlation back to your data source.