我正在使用开关控件,每当我从页面导航或重新启动应用程序时,它的值都会设置为默认“关闭”。如何克服它,以便如果按下它应该保持打开或者如果按下它应该保持关闭,直到我们手动更改?
这是我为滚动视图分配和设置 ffram 的代码
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell new";
listData =[self.tableContents objectForKey:[self.sortedgroups objectAtIndex:[indexPath section]]];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
}
NSUInteger row = [indexPath row];
cell.textLabel.text = [listData objectAtIndex:row];
if(indexPath.section==0)
{
switch (indexPath.row)
{
case 0:
{
switcher = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease];
[switcher addTarget:self action:@selector(switchAction:)
forControlEvents:UIControlEventValueChanged];
cell.accessoryView = switcher;
switcher.tag = indexPath.row;
//cell.textLabel.text=@"switcher";
}
break;
case 1:
{
slide = [[[UISlider alloc] initWithFrame:CGRectMake(0,0, 150, 15)] autorelease];
[slide addTarget:self action:@selector(slideact:)
forControlEvents:UIControlEventValueChanged];
cell.accessoryView = slide;
// slide.tag = indexPath.row;
}
break;
}
}
}
这是我的切换操作方法:
- (void)switchAction:(UISwitch*)sender
{
NSLog(@"switchAction: sender = %d, isOn %d", [sender tag], [sender isOn]);
if(sender.on)
{
[[NSUserDefaults standardUserDefaults]setObject:@"on" forKey:@"switcher"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
else
{
[[NSUserDefaults standardUserDefaults]setObject:@"off" forKey:@"switcher"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
}
-(void)viewWillAppear:(BOOL)animated
{
if ([[[NSUserDefaults standardUserDefaults]valueForKey:@"switcher"]isEqualToString:@"on"])
{
switcher.on=YES;
}
else
{
switcher.on=NO;
}
}