スタティック セルを介してストーリーボードに作成した TableView があります。
セクションには、ラベルとスイッチを含む単一の行があるという考え方です。ユーザーがスイッチを「オン」にすると、セクションの下にいくつかの新しい行が表示されます。設定アプリの Wi-Fi 設定と多少似ています (新しいセクションを追加しますが、新しい行を追加しています)。
次のように、ストーリーボードを介してこの TableView を作成しています。
次に、スイッチ値が変更されたときに実行されるアクション:
- (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];
}
これらの新しい行のセルを表示するために、通常のテーブル ビュー データ ソース メソッドが呼び出されることを期待しているので、次のコードを追加しました。
- (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;
}
}
しかし、私の便利なデバッガによると、 tableView:numberOfRowsInSection: が呼び出され、値が返され、 tableView:cellForRowAtIndexPath が呼び出される前にアプリがクラッシュします。
2012-08-02 13:16:08.564 TableViewInsertTest[3186:f803] * キャッチされていない例外 'NSRangeException' が原因でアプリを終了しています。理由: '* -[__NSArrayI objectAtIndex:]: 境界を超えたインデックス 1 [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)
これを機能させるために他に何かする必要がありますか、または実装しようとしている動作のタイプがサポートされていませんか?