开/关声音(IOS)

时间:2017-08-05 14:59:26

标签: ios audio swift3 xcode8 calculator

按下时,我将此代码用于按下按键的按钮。

是否可以这样做,当你关闭" Switch" - (在第二个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 个答案:

答案 0 :(得分:2)

您可以将声音值存储在布尔值中,并在开关更改后将其保存在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
    }
}
相关问题