UICollectionViewCell 中的按钮在单击时发出键盘声音

Button in UICollectionViewCell Makes Keyboard Sound When Clicked

我有一个 UICollectionViewCell (CustomCell) 的子类,它有一个 UIButton (button),我想在按下它时播放声音.特别是,我希望在变量 isOn 变为 true 时播放键盘字母声音,并在变量 isOn 变为 [=19= 时播放键盘退格(或删除)声音].

到目前为止我有以下内容:

class CustomCell: UICollectionViewCell {

    private var isOn = true

    @IBOutlet weak private var button: UIButton! {
        didSet {
            button.addTarget(self, action: #selector(self.toggleButton), for: .touchUpInside)
        }
    }

    @objc private func toggleButton() {
        if (isOn) {
            /// Play keyboard backspace (delete) sound ...
            UIDevice.current.playInputClick()
        } else {
            /// Play keyboard text sound ...
            UIDevice.current.playInputClick()
        }
        isOn = !isOn
    }

}

我也实现了UIInputViewAudioFeedback协议如下:

extension CustomCell: UIInputViewAudioFeedback {
    func enableInputClicksWhenVisible() -> Bool {
        return true
    }
}

但是,按下按钮时没有声音。

感谢您的帮助。

要播放键盘字母的声音:-

enum SystemSound: UInt32 {

    case pressClick    = 1123
    case pressDelete   = 1155
    case pressModifier = 1156

    func play() {
        AudioServicesPlaySystemSound(self.rawValue)
    }

}

找到合适的声音细节here also

因此,将 UIDevice.current.playInputClick() 替换为 AudioServicesPlaySystemSound(systemSoundsID)

为了完整使用已接受的答案和原始问题:

import AudioToolbox
import UIKit

enum SystemSound: UInt32 {

    case click = 1123
    case delete = 1155
    case modifier = 1156

    func play() {
        AudioServicesPlaySystemSound(self.rawValue)
    }

}

class CustomCell: UICollectionViewCell {

    private var isOn = true

    @IBOutlet weak private var button: UIButton! {
        didSet {
            button.addTarget(self, action: #selector(self.toggleButton), for: .touchUpInside)
        }
    }

    @objc private func toggleButton() {
        isOn = !isOn
        let systemSound: SystemSound = (isOn) ? .click : .modifier
        systemSound.play()
    }

}