0

In my code when user adds a new item to the list, the App adds it to an array of items, sorts them, then calls [tableView reloadData]. Because of sorting the list, sometimes newly added item goes out of view. I'm going to get the UITableViewCell of newly added item when it's out of view and scroll it back into view.

In cellForRowAtIndexPath I add the record to tag of each cell:

cell.tag = listItems.recordID;

In addNewItem method after adding new item and sorting the items:

for (int i = 0; i<listItems.count; i++)
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    int tag = cell.tag;
    if (tag == newItemRecordID)
        [self.tableView scrollToRowAtIndexPath:indexPath
                              atScrollPosition:UITableViewScrollPositionMiddle
                                      animated:YES];
}

When the cell is out of view tag property returns 0 and I can't get the cell.

How is it possible do get that cell?

Lebyrt
  • 1,376
  • 1
  • 9
  • 18
Hadi Sharghi
  • 903
  • 16
  • 33
  • `cellForRowAtIndexPath:` returns nil for cells that are not currently visible, so your basic algorithm is faulty. Since all methods sent to nil return 0, tag will be 0 for any cells not currently visible. Lebyrt's solution should work. – David Berry May 06 '14 at 18:56

2 Answers2

1

I guess, it would be better to use something like this:

for (int i = 0; i < listItems.count; i++)
{
    // Replace 'ListItem' with the name of your class.
    ListItem *listItem = [listItems objectAtIndex:i];
    if (listItem.recordID == newItemRecordID)
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        [self.tableView scrollToRowAtIndexPath:indexPath
                              atScrollPosition:UITableViewScrollPositionMiddle
                                      animated:YES];
        break;
    }
}
Lebyrt
  • 1,376
  • 1
  • 9
  • 18
0

On cellForRowAtIndexPath set cell tag as the following:

cell.tag = indexPath.row;

After setting cell tag, you can call your function:

for (int i = 0; i<listItems.count; i++)
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    int tag = cell.tag;
    if (tag == newItemRecordID)
        [self.tableView scrollToRowAtIndexPath:indexPath
                              atScrollPosition:UITableViewScrollPositionMiddle
                                      animated:YES];
}
Suliman
  • 25
  • 5