如何保存/检索UIButton状态?

时间:2010-10-16 12:12:44

标签: iphone uibutton uiswitch

这是我的第一个问题!

我使用UIButton和UISwitch功能,我想保存/检索UIButton的状态。 请帮助!

解决!

  

感谢Kalle和aBitObvious!

我使用的代码:

·H

@interface RetinaViewController : UIViewController {
IBOutlet UIButton *mybutton;

}

-(IBAction) toggleUIButtonImage:(id)sender;


@end

的.m

@implementation RetinaViewController

-(IBAction) toggleUIButtonImage:(id)sender{
NSString *value = @"ON";
NSUserDefaults *userPreferences = [NSUserDefaults standardUserDefaults];
UIImage *unselectedImage = [UIImage imageNamed: @"OFFa.png"];
UIImage *selectedImage = [UIImage imageNamed:@"ONa.png"];
    if ([sender isSelected]) {
    [sender setImage:unselectedImage forState:UIControlStateNormal];
    [sender setSelected:NO];
        value = @"OFF";
        [userPreferences setObject:value forKey:@"stateOfButton"];
}else {
    [sender setImage:selectedImage forState:UIControlStateSelected];
    [sender setSelected:YES];
    value = @"ON";
    [userPreferences setObject:value forKey:@"stateOfButton"];
}

[userPreferences synchronize];
}



- (void)viewDidLoad {

NSString *value = [[NSUserDefaults standardUserDefaults]  stringForKey:@"stateOfButton"];

// If value is nil - disable the switch
if (value == nil) { 
    mybutton.selected = NO;
}
// If value is equal to ON
else if ([value compare:@"ON"] == NSOrderedSame) {

    //NSLog(@"the switch is on");

    // Set the switch to ON
    mybutton.selected = YES;

} else {

    //NSLog(@"the switch is off");

    // Set the switch to OFF
    mybutton.selected = NO;
}


    [super viewDidLoad];
}

1 个答案:

答案 0 :(得分:0)

在视图控制器的viewDidLoad中,输入如下内容:

NSUserDefaults *userPreferences = [NSUserDefaults standardUserDefaults];
NSString *stateOfButton = [userPreferences stringForKey:@"stateOfButton"];
if ([stateOfButton isEqualToString:@"ON"])
{
    //set button state to "selected"
}
else
{
    //set button state to "not selected"
}