Search code examples
iosxcodetableviewdidselectrowatindexpath

TableView: How to select another row's value from didSelectRowAtIndexPath routine


When didSelectRowAtIndexPath is called, it's easy to get a cell's text value using: UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; entryText = cell.textLabel.text;

However, I'm having a problem figuring out how to get the cell text value from another row at the same time. For instance, if a user clicks on row 0, the above will get me the cell text from row 0. But I need to get the cell text from row 1 and row 2.

How do I do that?


Solution

  • If you create your own IndexPath variable for those cells, for example:

    NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:indexPath.section];
    UITableViewCell *cell1 = [self.tableView cellForRowAtIndexPath:indexPath1];
    NSString *cell1Text = [NSString stringWithString: cell1.textLabel.text];
    
    NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:indexPath.row+2 inSection:indexPath.section];
    UITableViewCell *cell2 = [self.tableView cellForRowAtIndexPath:indexPath2];
    NSString *cell2Text = [NSString stringWithString: cell2.textLabel.text];
    

    That should do the trick.