我有一个奇怪的问题(至少在我看来)。当我将 UISwitch 添加到我的表格视图时,当用户滚动表格视图时,开关会自动更改单元格。下面是我如何为 tableview 创建 UISwitch 的代码。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//NSLog(@"This is what we are looking for %@ %@", checkUsername, checkPassword);
// Configure the cell...
NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section];
NSArray *array =[dictionary objectForKey:@"Settings"];
NSString * cellValue = [array objectAtIndex:indexPath.row];
static NSString *CellIdentifier = @"Cell";
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.accessoryView = nil;
if (!cell) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
//switcher.on = [[NSUserDefaults standardUserDefaults]boolForKey:@"Settings"];
if (section == 1)
{
UISwitch *switchView = [[UISwitch alloc] init];
cell.accessoryView = switchView;
[switchView setOn:YES animated:NO];
[switchView setTag:[indexPath row]];
[switchView addTarget:self action:@selector(switchWasChangedFromEnabled:) forControlEvents:UIControlEventValueChanged];
//[self.tableView reloadData];
[switchView release];
}
}
return cell;
}
有人可以告诉我为什么开关不断移出指定的单元格以及可能的补救措施。
贾斯汀加拉格尔建议:
发生这种情况是因为您正在缓存单元格并重用它们。有时,带有开关的单元会在另一个地方重复使用。尝试使用开关为单元格设置不同的标识符。
但是有人可以告诉我如何为每个单元格设置不同的标识符吗?
干杯,
我明白