当我的 NavigationController 中的后退按钮被按下时,找不到如何添加播放声音。
我在 NavigationVC 中有一些 VC。我没有自定义 NavigationVC,但我在其堆栈上的第一个 VC 中设置了 NavigationVC 的后退按钮。我正在尝试在此按钮的操作中添加 func 播放声音。但它不叫。
这是我的代码。这是 NavigationVC 的第一个 ViewController:
override func viewDidLoad() {
super.viewDidLoad()
// some another code
// set back button for Navigation Controller
self.navigationController?.navigationBar.backIndicatorImage = UIImage(named: "backButtonIcon")
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "backButtonIcon")
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItem.Style.plain, target: self, action: #selector(backButtonPressed))
self.navigationItem.backBarButtonItem?.action = #selector(backButtonPressed)
}
// this func isn't called, but has to be
@objc func backButtonPressed() {
print("back button pressed")
Sounds.playSound(Sounds.tap)
}
这里是声音。这是 AppDelegate 文件中的结构。我使用静态属性和函数,所以我不创建这个结构的实例;
struct Sounds {
static let lose = Bundle.main.url(forResource: "lose", withExtension: "mp3")
static let win = Bundle.main.url(forResource: "win", withExtension: "mp3")
static let select = Bundle.main.url(forResource: "select", withExtension: "mp3")
static let deSelect = Bundle.main.url(forResource: "unSelect", withExtension: "mp3")
static let tap = Bundle.main.url(forResource: "tap", withExtension: "mp3")
static var soundsIsDisabled = UserDefaults.init().bool(forKey: "sounds is disabled") {
didSet {
UserDefaults.init().set(soundsIsDisabled, forKey: "sounds is disabled")
}
}
static func playSound(_ sound: URL?) {
if !Sounds.soundsIsDisabled {
guard let url = sound else { return }
do {
AppDelegate.audioPlayer = try AVAudioPlayer(contentsOf: url)
try AVAudioSession.sharedInstance().setCategory(.ambient, mode: .default, options: .defaultToSpeaker)
try AVAudioSession.sharedInstance().setActive(true)
AppDelegate.audioPlayer.prepareToPlay()
}
catch{
print(error)
}
AppDelegate.audioPlayer.play()
}
}
}
如您所见,我的目标是在 NavigationVC 中的所有 VC 的后退按钮上添加点击声音。
怎样才能实现呢?