2012年7月31日 星期二

Cocos2d 2.0 Menu Item Toggle


Set Default Value for Settings

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *soundOnKey = [NSString stringWithString:@"sound_on"];
NSNumber *soundOnValue = [NSNumber numberWithInt:0];
NSDictionary *defaultSoundOnValue = [NSDictionary dictionaryWithObject:soundOnValue forKey:soundOnKey];
[defaults registerDefaults:defaultSoundOnValue];

Declare public variable

CCMenuItem *sound_control_on;
CCMenuItem *sound_control_off;

Create Toggle Item

sound_control_on = [CCMenuItemImage itemWithNormalImage:@"sound_control_on.png" selectedImage:@"sound_control_on_pressed.png" target:nil selector:nil];
sound_control_off = [CCMenuItemImage itemWithNormalImage:@"sound_control_off.png" selectedImage:@"sound_control_off_pressed.png" target:nil selector:nil];
CCMenuItemToggle *sound_control_toggle = [CCMenuItemToggle itemWithTarget:self selector:@selector(sound_control:) items:sound_control_on, sound_control_off, nil];
sound_control_toggle.position = ccp(0, -55);
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *soundOnKey = [NSString stringWithString:@"sound_on"];
[sound_control_toggle setSelectedIndex:[defaults integerForKey:soundOnKey]];

Toggle Handler

-(void) sound_control:(id)sender {
    CCMenuItemToggle *item = (CCMenuItemToggle *)sender;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *soundOnKey = [NSString stringWithString:@"sound_on"];
    NSNumber *soundOnValue;
    if (item.selectedItem == sound_control_on) {
        soundOnValue = [NSNumber numberWithInt:0];
    } else {
        soundOnValue = [NSNumber numberWithInt:1];
    }
    [defaults setInteger:soundOnValue.intValue forKey:soundOnKey];
}


沒有留言:

張貼留言