Toggle switch to turn off application sounds

2019-06-08 01:47发布

I have multiple sounds in my application. I want to setup a toggle switch in settings to turn these sounds off. Here is the code that executes the sounds.

- (void) soundEventDidHappen:(NSString*)eventName {
//check dictionary of sounds.. if there is a corresponding sound for this event name, play it

if ([[soundIDForEventString allKeys] containsObject:eventName]) {
    AudioServicesPlaySystemSound ([[soundIDForEventString objectForKey:eventName] intValue]);
}

标签: ios toggle
1条回答
Root(大扎)
2楼-- · 2019-06-08 01:57

You could make a simple toggle like this:

bool isToggled;

- (IBAction) toggleSound{
    if(isToggled){
        isToggled = NO; //sets isToggled to false if it's already true
    }
    else{
        isToggled = YES; //sets isToggled to true if it's already false
    }
}

and then you could just do:

- (void) soundEventDidHappen:(NSString*)eventName {
    //check dictionary of sounds.. if there is a corresponding sound for this event name, play     it
    if(isToggled){

        if ([[soundIDForEventString allKeys] containsObject:eventName]) {
        AudioServicesPlaySystemSound ([[soundIDForEventString objectForKey:eventName] intValue]);
        }
    }
}

Which will play the sound if isToggled is true. You could then use NSUserDefaults if you would like to save the boolean for the future:

[[NSUserDefaults standardUserDefaults] setBool:isToggled forKey:@"soundEnabled"];
[[NSUserDefaults standardUserDefaults] synchronize];

//use this to save

Then you could use this to get the value (most likely somewhere in your viewDidLoad method:

isToggled = [[NSUserDefaults standardUserDefaults] boolForKey:@"soundEnabled"];
[[NSUserDefaults standardUserDefaults] synchronize];
查看更多
登录 后发表回答