NavigationController の戻るボタンが押されたときに、再生音を追加する方法がわかりません。
NavigationVC にいくつかの VC があります。NavigationVC はカスタマイズしませんでしたが、NavigationVC の戻るボタンをスタックの最初の VC に設定しました。このボタンのアクションに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 の backButtons にタップ音を追加することです。
どうすればそれを達成できますか?