Friday, June 7, 2013

UITableView visibleCells example in Objective C (iOS).


UITableView visibleCells

Returns the table cells that are visible in the receiver.

- (NSArray *)visibleCells

Return Value of [UITableView visibleCells]
An array containing UITableViewCell objects, each representing a visible cell in the receiving table view.

UITableView visibleCells example.
- (void)checkVisibilityOfCell:(MyCustomUITableViewCell *)cell inScrollView:(UIScrollView *)aScrollView {
    CGRect cellRect = [aScrollView convertRect:cell.frame toView:aScrollView.superview];

    if (CGRectContainsRect(aScrollView.frame, cellRect))
        [cell notifyCompletelyVisible];
    else
        [cell notifyNotCompletelyVisible];
}

- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {
    NSArray* cells = myTableView.visibleCells;

    NSUInteger cellCount = [cells count];
    if (cellCount == 0)
        return;

    // Check the visibility of the first cell
    [self checkVisibilityOfCell:[cells firstObject] inScrollView:aScrollView];
    if (cellCount == 1)
        return;

    // Check the visibility of the last cell
    [self checkVisibilityOfCell:[cells lastObject] inScrollView:aScrollView];
    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 < cellCount - 1; i++)
        [[cells objectAtIndex:i] notifyCompletelyVisible];
}

Example of [UITableView visibleCells].
- (void)loadContentForVisibleCellsInSection{

    NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
    for (NSIndexPath *indexPath in visiblePaths)
    {
        switch (indexPath.section) {
            case 0:{   
                CustomCell *cell = (CustomCell *)[self.tableView cellForRowAtIndexPath:indexPath];
                [cell loadImage];
            }              
                break;
            default:
                break;
        }

    }

}

UITableView visibleCells example.
if ([tableView visibleCells] containsObject: theCellOfInterest]) {
    // Do whatever you want to do.
}

End of UITableView visibleCells example article.