我正在使用开关控件,无论何时从页面导航或重新启动应用程序,其值都设置为默认“关闭”。如何克服这个问题,如果按下它应该保持开启状态,或者如果按下它应该保持关闭状态,直到我们手动更改为止。如何在应用程序中保存开关的状态
这里是我的代码,在那里我分配和了滚动
- (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;
//[email protected]"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;
}
}
}
设置ffram这是我对开关的操作方法:
- (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;
}
}
我试过你的代码,谢谢你的时间,但是当我使用表格视图时,当我打开开关如果我滚动表格,开关按钮会自动设置为关闭。你能帮我吗 – sujay 2011-05-21 09:47:54
看到我已经投票了你,我已经用代码编辑了我的问题,请检查.. – sujay 2011-05-21 09:59:02