如何使用可在NSUserDefaults中保存值的开关显示/隐藏按钮

时间:2012-05-03 16:34:12

标签: ios xcode uibutton nsuserdefaults uiswitch

UISwitch 命名 sosSwitch 可以在 NSUserDefaults 键中保存价值: MySwitch ,我有 UIButton 命名为 sosBtn 。 如何显示/隐藏 sosBtn ,具体取决于 NSUserDefaults 中保存的切换值?我需要把代码放在哪里?在viewDidLoad中?谢谢!

1 个答案:

答案 0 :(得分:2)

假设你已经拥有:

@property (retain, nonatomic) IBOutlet UIButton *sosBtn;
@property (retain, nonatomic) IBOutlet UISwitch *sosSwich;
- (IBAction)sosSwitch:(id)sender;

试试这个:

-(void)viewDidLoad
{    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"MySwitch"])
    {
        self.sosBtn.hidden = NO;
        [self.sosSwich setOn:YES animated:YES]; 
    }
    else 
    {
        self.sosBtn.hidden = YES;
        [self.sosSwich setOn:NO animated:YES];
    }
}

- (IBAction)sosSwitch:(id)sender 
{
    UISwitch *mySosSwitch = (UISwitch *)sender;
    if (mySosSwitch.on)
    {
        self.sosBtn.hidden = NO;
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"MySwitch"];  //YES means sosBtn should be visible
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    else 
    {
        self.sosBtn.hidden = YES;
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"MySwitch"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}