Determine if a tableview cell is visible
Is there any way to know if a tableview cell is currently visible? I have a tableview whose first cell(0) is a uisearchbar. If a search is not active, then hide cell 0 via an offset. When the table only has a few rows, the row 0 is visible. How to determine if row 0 is visible or is the top row?
Solution 1:
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.
Solution 2:
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
}
Solution 3:
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 }
} }
Solution 4:
Swift Version:
if let indices = tableView.indexPathsForVisibleRows {
for index in indices {
if index.row == 0 {
return true
}
}
}
return false