0

我有名为sosSwitch的UISwitch ,它保存了 NSUserDefaults 键中的值 MySwitch 我有名为sosBtn的UIButton。如何根据保存在 NSUserDefaults 中的开关值显示/隐藏sosBtn?我需要把代码放在哪里?在 viewDidLoad? 谢谢!

4

1 回答 1

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];
    }
}
于 2012-05-03T19:50:28.807 回答