Reputation: 3058
I have a subclass of UICollectionViewCell
(CustomCell
), which has a single UIButton
(button
) that I want to play a sound when it is pressed. In particular, I want the keyboard letter sounds to play when the variable isOn
turns to true
and the keyboard backspace (or delete) sound to play when variable isOn
turns to false
.
So far I have the following:
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
}
}
I also implement the UIInputViewAudioFeedback
protocol as follows:
extension CustomCell: UIInputViewAudioFeedback {
func enableInputClicksWhenVisible() -> Bool {
return true
}
}
However, no sound is made when the button is pressed.
Thanks for any help.
Upvotes: 0
Views: 223
Reputation: 3058
For completeness using the accepted answer and the original question:
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()
}
}
Upvotes: 0
Reputation: 8516
To play keyboard letter sounds :-
enum SystemSound: UInt32 {
case pressClick = 1123
case pressDelete = 1155
case pressModifier = 1156
func play() {
AudioServicesPlaySystemSound(self.rawValue)
}
}
Find proper sound details here also.
So, replace UIDevice.current.playInputClick()
with AudioServicesPlaySystemSound(systemSoundsID)
Upvotes: 1