Friday, June 7, 2013

UITableView indexPathForCell example in Objective C (iOS).


UITableView indexPathForCell

Returns an index path representing the row and section of a given table-view cell.

- (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell

Parameters
cell
A cell object of the table view.

Return Value of [UITableView indexPathForCell]
An index path representing the row and section of the cell or nil if the index path is invalid.

UITableView indexPathForCell example.
- (void)textFieldDidEndEditing:(UITextField *)textField
{
CustomCell *cell = (CustomCell *) textField.superview.superview;

NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

NSLog(@"the section is %d and row is %d", indexPath.section, indexPath.row);
...
}

Example of [UITableView indexPathForCell].
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    UITableView *tableView;
    UITableViewCell* superViewCell = [self returnSuperCellViewOfTextField:textField];
    if(superViewCell)[tableView scrollToRowAtIndexPath:[tableView indexPathForCell:superViewCell] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}

-(id)returnSuperCellViewOfTextField:(id)viewToCheck
{
    id superView = [viewToCheck superview];
    if([viewToCheck isKindOfClass:[UITableViewCell class]] && superView)return superView;
    else if(([viewToCheck respondsToSelector:@selector(superview)] && superView)) return [self returnSuperCellViewOfTextField:superView];
    return nil;
}

UITableView indexPathForCell example.
NSIndexPath *indexPath = [(UITableView *)self.superview indexPathForCell: self];
int rows = [(UITableView *)self.superview numberOfRowsInSection:indexPath.section];

if (indexPath.row == 0 && rows == 1) {
// the one and only cell in the section
}
else if (indexPath.row == 0) {
//top
}
else if (indexPath.row != rows - 1) {
//middle
}
else {
//bottom
}

End of UITableView indexPathForCell example article.