我有一个UICollectionViewCell
(CustomCell
)的子类,它有一个UIButton
(button
),我想在按下时发出声音。特别是,当变量isOn
变为true
时,我希望键盘字母发出声音,当变量isOn
变为false
时,键盘退格(或删除)声音播放}。
到目前为止,我有以下内容:
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
}
}
然而,按下按钮时没有声音。
感谢您的帮助。
答案 0 :(得分:1)
播放键盘字母声音: -
enum SystemSound: UInt32 {
case pressClick = 1123
case pressDelete = 1155
case pressModifier = 1156
func play() {
AudioServicesPlaySystemSound(self.rawValue)
}
}
找到合适的声音详情here also。
因此,请将UIDevice.current.playInputClick()
替换为AudioServicesPlaySystemSound(systemSoundsID)
答案 1 :(得分:0)
为了使用已接受的答案和原始问题的完整性:
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()
}
}