Ios UICollectionViewCell中的按钮在单击时发出键盘声音
我有一个子类Ios UICollectionViewCell中的按钮在单击时发出键盘声音,ios,swift,uibutton,uicollectionviewcell,Ios,Swift,Uibutton,Uicollectionviewcell,我有一个子类UICollectionViewCell(CustomCell),它有一个UIButton(button)我想在按下时播放声音。特别是,我希望在变量isOn变为true时播放键盘字母声音,在变量isOn变为false时播放键盘退格(或删除)声音 到目前为止,我有以下几点: class CustomCell: UICollectionViewCell { private var isOn = true @IBOutlet weak private var butto
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
}
}
但是,按下按钮时不会发出声音
感谢您的帮助。要播放键盘字母声音:-
enum SystemSound: UInt32 {
case pressClick = 1123
case pressDelete = 1155
case pressModifier = 1156
func play() {
AudioServicesPlaySystemSound(self.rawValue)
}
}
找到合适的声音细节
因此,将
ui设备.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()
}
}
非常感谢你。这是可行的,但是您还必须导入AudioToolbox。您的代码不起作用,因为它仅在符合
UIInputViewAudioFeedback
的视图是文本字段或文本视图的inputView
时才起作用。