[英]Button in UICollectionViewCell Makes Keyboard Sound When Clicked
我有一个UICollectionViewCell
( CustomCell
)的子类,它有一个UIButton
( button
),我想在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)
}
}
在这里也可以找到合适的声音细节。
因此,将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()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.