2017-08-05 327 views
0

按下此按钮时使用此代码按下按钮。打开/关闭声音(IOS)

是否可以这样做,当您关闭“开关”(位于第二个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 
    } 
}