2

I've got a TableView that I've created in a Storyboard via Static Cells.

The idea is that a section has a single row with a Label and a Switch. When the user taps the Switch "on", the section sprouts some new rows below. Somewhat similar to Wi-Fi settings in the Settings app (which adds new sections, but I'm adding new rows).

enter image description here

I'm creating this TableView via Storyboard like so:

enter image description here

And now, the action taken when the switch value changes:

- (IBAction)hitSwitch:(id)sender {

    NSArray *indexPathsArray = [NSArray arrayWithObjects:[NSIndexPath indexPathForRow:1 inSection:0], [NSIndexPath indexPathForRow:2 inSection:0], nil];



    UISwitch *theSwitch = sender;

    [self.tableView beginUpdates];

    if (theSwitch.on) {

        [self.tableView insertRowsAtIndexPaths:indexPathsArray withRowAnimation:UITableViewRowAnimationAutomatic];

    } else {

        [self.tableView deleteRowsAtIndexPaths:indexPathsArray withRowAnimation:UITableViewRowAnimationAutomatic];

    }

    [self.tableView endUpdates];

}

I'd expect the normal table view data source methods to be called to display the cells for these new rows, so I've added the following code:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (self.addRowsSwitch.on) {

        return 3;

    } else {

        return [super tableView:tableView numberOfRowsInSection:section];

    }

}



- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (!self.addRowsSwitch.on) {

        return [super tableView:tableView cellForRowAtIndexPath:indexPath];

    } else {

        UITableViewCell *newCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];

        return newCell;

    }

}

But according to my handy debugger, tableView:numberOfRowsInSection: is called, returns a value, and then the app crashes before tableView:cellForRowAtIndexPath is called.

2012-08-02 13:16:08.564 TableViewInsertTest[3186:f803] * Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]' *** First throw call stack: (0x14b2022 0xeb2cd6 0x149e644 0x43bea5 0x2481a8 0x1f3688 0x1f4c2a 0x9743e 0xa50b7 0xa50e5 0x2604 0x14b3e99 0x1814e 0x180e6 0xbeade 0xbefa7 0x212c16 0x93b85d 0x1486936 0x14863d7 0x13e9790 0x13e8d84 0x13e8c9b 0x139b7d8 0x139b88a 0x15626 0x1ebd 0x1e25)

Is there something else I need to do to make this work, or is the type of behaivor that I'm trying to implement not supported?

bpapa
  • 21,409
  • 25
  • 99
  • 147
  • possible duplicate of [Adding unknown number of rows to 'Static Cells' UITableView](http://stackoverflow.com/questions/10043521/adding-unknown-number-of-rows-to-static-cells-uitableview) – bpapa Aug 02 '12 at 18:47

0 Answers0