切换开关以关闭应用程序声音

时间:2014-01-06 23:20:40

标签: ios toggle

我的应用程序中有多个声音。我想在设置中设置一个切换开关以关闭这些声音。这是执行声音的代码。

- (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]);
}

1 个答案:

答案 0 :(得分:1)

您可以像这样进行简单的切换:

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
    }
}

然后你可以这样做:

- (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]);
        }
    }
}

如果isToggled为真,那将播放声音。如果您希望保存未来的布尔值,则可以使用NSUserDefaults

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

//use this to save

然后您可以使用它来获取值(很可能是viewDidLoad方法中的某个位置:

isToggled = [[NSUserDefaults standardUserDefaults] boolForKey:@"soundEnabled"];
[[NSUserDefaults standardUserDefaults] synchronize];