1

我是 iphone 新手。我有一点疑问,当我们单击该按钮时,我有一个名为 Sync 的按钮,以下操作将执行:

- (IBAction)syncOffClickedInRegisterUserScreen:(id)sender {
    if ([syncOnorOff.titleLabel.text isEqualToString:@"Sync off"]) {
        [syncOnorOff setTitle:@"Sync on" forState:UIControlStateNormal];
    } 
    else {
        [syncOnorOff setTitle:@"Sync off" forState:UIControlStateNormal];
    }
}

由于上面的代码,当我单击按钮时,标题会交替出现。

如何使用 NSUserDefaults 保存具有不同标题的按钮状态。如果有人知道这个请帮助我....

4

2 回答 2

4

您需要定义一个键来保存此按钮示例:

 #define KEYSTATE @"key.syncState"

并在您的功能中:

-  (IBAction)syncOffClickedInRegisterUserScreen:(id)sender {

    // Get User Defaults
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

    if ([syncOnorOff.titleLabel.text isEqualToString:@"Sync off"]) {
        [prefs setBool:NO forKey:KEYSTATE];
        [syncOnorOff setTitle:@"Sync on" forState:UIControlStateNormal];
    } 
    else {
        [prefs setBool:YES forKey:KEYSTATE];
        [syncOnorOff setTitle:@"Sync off" forState:UIControlStateNormal];
    }

    // save 
    [prefs synchronize];
}

然后你可以得到布尔(viewDidLoad:例如)来设置按钮,如下所示:

if ([[NSUserDefaults standardUserDefaults] boolForKey:KEYSTATE]) {
    // Set ON
}
else {
    // Set OFF
}
于 2012-05-16T09:27:45.197 回答
0
UIButton *button;

// get nsuserdefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// save selected state
[defaults setBool:button.selected forKey:@"myButtonState"];

然后稍后,在应用程序再次启动后......

// restore the selected state
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
button.selected = [defaults boolForKey:@"myButtonState"];
于 2017-06-05T13:49:21.377 回答