Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios UICollectionViewCell中的按钮在单击时发出键盘声音_Ios_Swift_Uibutton_Uicollectionviewcell - Fatal编程技术网

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
时才起作用。