我希望 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();
}
}