views:

364

answers:

2

I currently have a UISegmentedControl set to add/remove table view cells when its value changes. Removing cells works perfectly, however when I insert cells they're in reverse order every other time.

NSArray *addindexes = [NSArray arrayWithObjects:[NSIndexPath indexPathForRow:2 inSection:0], [NSIndexPath indexPathForRow:3 inSection:0], [NSIndexPath indexPathForRow:4 inSection:0], nil];
NSArray *removeindexes = [NSArray arrayWithObjects:[NSIndexPath indexPathForRow:2 inSection:0], [NSIndexPath indexPathForRow:3 inSection:0], [NSIndexPath indexPathForRow:4 inSection:0], nil];
[self.tableView beginUpdates];

switch (switchType.selectedSegmentIndex) {
    case 0:
        [self.tableView insertRowsAtIndexPaths:addindexes withRowAnimation:UITableViewRowAnimationTop];
        break;
    case 1:
        [self.tableView deleteRowsAtIndexPaths:removeindexes withRowAnimation:UITableViewRowAnimationTop];

        break;
    default:
        break;
}

[self.tableView endUpdates];}

For example, every other time I add/remove cells they're in reverse order. (4, 3, 2 instead of 2, 3, 4)
1) Remove cells- add cells- correct order
2) Remove cells- add cells- incorrect order
3) Remove cells- add cells- correct order

+1  A: 

All that your code sample shows is the indexes. The display order of the cells is determined by your tableView:cellForRowAtIndexPath: method.

drawnonward
Yes, I realize this but there isn't a reason why this would cause the order of the cells to change. Unless I'm missing something huge.I have tableView:cellForRowAtIndexPath set up with switch(indexPath.row). The problem is the display order changes.
Brandon Schlenker
Never mind. Got it working. Thanks for the help.
Brandon Schlenker
Can you elaborate?
Kamchatka
A: 

Each cell created a UITextField. To prevent this from being drawn multiple times I used

if (!someTextField)

This caused the cell not to be updated since the text field was already drawn. To solve the issue I simply added [someTextField removeFromSuperview] as the row was being deleted.

Brandon Schlenker