2017-08-05 4 views
0

このコードは、押されたときに押す音のボタンに使用します。オン/オフ音(IOS)

「スイッチ」(2番目のVCにある)をオフにすると、最初のVCのボタンの音が消えますか?

[VC1 and VC2

@IBAction func SoundButton(_ sender: UIButton) { 
    let filename = "button-16" 
    let ext = "mp3" 

    if let soundUrl = Bundle.main.url(forResource: filename, withExtension: ext) { 
     var soundId: SystemSoundID = 0 

     AudioServicesCreateSystemSoundID(soundUrl as CFURL, &soundId) 

     AudioServicesAddSystemSoundCompletion(soundId, nil, nil, { (soundId, clientData) -> Void in 
      AudioServicesDisposeSystemSoundID(soundId) 
     }, nil) 

     AudioServicesPlaySystemSound(soundId) 
    } 
} 

答えて

1

あなたはブール値で、音の値を格納してスイッチが変化した後UserDefaultsに保存することができます。このブール値を取得し、スイッチの状態をcellForRowAtに設定する必要があります。

GlobalVariables.swift

var isSoundOn: String { 
    get { 
     return UserDefaults.standard.bool(forKey: "isSoundOn") 
    } 

    set { 
     UserDefaults.standard.setBool(newValue, forKey: "isSoundOn") 
     UserDefaults.standard.synchronize() 
    } 
} 

CalculatorViewController.swift

@IBAction func soundButtonPressed(_ sender: UIButton) { 
    guard isSoundOn else { 
     return 
    } 

    let filename = "button-16" 
    let ext = "mp3" 

    [...] 
} 

SettingsViewController.swift

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let settingCell = tableView.dequeueReusableCell(withIdentifier: "settingCell", for: indexPath) as! SettingCell 
    settingCell.switch.isOn = isSoundOn 

    return settingCell 
} 

SettingCell.swift

class SettingCell: UITableViewCell { 
    @IBOutlet weak var switch: UISwitch! 

    @IBAction func switchValueChanged() { 
     isSoundOn = switch.isOn 
    } 
}