0

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.

ajrlewis
  • 2,968
  • 3
  • 33
  • 67
  • Your code didn't work because it only works when the view conforming to `UIInputViewAudioFeedback` is the `inputView` of a text field or text view. – rmaddy Jun 13 '18 at 05:31

2 Answers2

1

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)

pkc456
  • 8,350
  • 38
  • 53
  • 109
0

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()
    }

}
ajrlewis
  • 2,968
  • 3
  • 33
  • 67