TableViewCell 内の UISwitch でテキストを「アクティブ」から「無効」に変更したいのですが、スイッチが変更されると、テーブル ビューのすべてのデータが消えます。特定のセルのテキストを変更する方法がわからないため、「データの再読み込み」を使用しています。
参考までに、「現在のアイテム」は、BOOL プロパティ「itemEnabled」を持つコア データ エンティティです。
スイッチは「編集モード」の間のみ表示されます。
「詳細ビュー コントローラー」内のテーブル ビュー セルに UISwitch があります。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
NSString *cellDetail = nil;
static NSString *EnabledCellIdentifier = @"Enabled";
cell = [tableView dequeueReusableCellWithIdentifier:EnabledCellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:EnabledCellIdentifier] autorelease];
UISwitch* actSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
[cell setEditingAccessoryView:actSwitch];
[actSwitch addTarget:self action:@selector(actSwitchChanged:) forControlEvents:UIControlEventValueChanged];
if ([[currentItem valueForKey:@"itemEnabled"] boolValue]) {
cellDetail = @"Active";
actSwitch.on = YES;
} else {
cellDetail = @"Disabled";
actSwitch.on = NO;
}
[actSwitch release];
cell.textLabel.text = cellDetail;
return cell;
}
アクションを受け取る方法があります:
- (void)actSwitchChanged:(id)sender {
UISwitch* swEnabled = (UISwitch*)sender;
NSManagedObjectContext* itemContext = [currentItem managedObjectContext];
currentItem.itemEnabled = [NSNumber numberWithBool:swEnabled.on];
NSError *error = nil;
if (![itemContext save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}