我正在使用開關控件,無論何時從頁面導航或重新啓動應用程序,其值都設置爲默認「關閉」。如何克服這個問題,如果按下它應該保持開啓狀態,或者如果按下它應該保持關閉狀態,直到我們手動更改爲止。如何在應用程序中保存開關的狀態
這裏是我的代碼,在那裏我分配和了滾動
- (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