Note that there are some explanatory texts on larger screens.

plurals
  1. POBest way to check if UITableViewCell is completely visible
    primarykey
    data
    text
    <p>I have a UITableView with cells of different heights and I need to know when they are <strong>completely</strong> visible or not.</p> <p>At the moment I am looping through each cell in the list of visible cells to check if it is completely visible every time the view is scrolled . Is this the best approach?</p> <p>Here's my code:</p> <pre><code>- (void)scrollViewDidScroll:(UIScrollView *)aScrollView { CGPoint offset = aScrollView.contentOffset; CGRect bounds = aScrollView.bounds; NSArray* cells = myTableView.visibleCells; for (MyCustomUITableViewCell* cell in cells) { if (cell.frame.origin.y &gt; offset.y &amp;&amp; cell.frame.origin.y + cell.frame.size.height &lt; offset.y + bounds.size.height) { [cell notifyCompletelyVisible]; } else { [cell notifyNotCompletelyVisible]; } } } </code></pre> <p><strong>Edit:</strong></p> <p>Please note that *- (NSArray <em>)visibleCells</em> returns visible cells which are both completely visible and partly visible.</p> <p><strong>Edit 2:</strong></p> <p>This is the revised code after combining solutions from both <em>lnafziger</em> and <em>Vadim Yelagin</em>:</p> <pre><code>- (void)scrollViewDidScroll:(UIScrollView *)aScrollView { NSArray* cells = myTableView.visibleCells; NSArray* indexPaths = myTableView.indexPathsForVisibleRows; NSUInteger cellCount = [cells count]; if (cellCount == 0) return; // Check the visibility of the first cell [self checkVisibilityOfCell:[cells objectAtIndex:0] forIndexPath:[indexPaths objectAtIndex:0]]; if (cellCount == 1) return; // Check the visibility of the last cell [self checkVisibilityOfCell:[cells lastObject] forIndexPath:[indexPaths lastObject]]; if (cellCount == 2) return; // All of the rest of the cells are visible: Loop through the 2nd through n-1 cells for (NSUInteger i = 1; i &lt; cellCount - 1; i++) [[cells objectAtIndex:i] notifyCellVisibleWithIsCompletelyVisible:YES]; } - (void)checkVisibilityOfCell:(MultiQuestionTableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath { CGRect cellRect = [myTableView rectForRowAtIndexPath:indexPath]; cellRect = [myTableView convertRect:cellRect toView:myTableView.superview]; BOOL completelyVisible = CGRectContainsRect(myTableView.frame, cellRect); [cell notifyCellVisibleWithIsCompletelyVisible:completelyVisible]; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload