1

当我的 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 的后退按钮上添加点击声音。

怎样才能实现呢?

4

1 回答 1

0

我在评论中发送的帖子中找到了解决方案。这篇文章

我没有完全理解,那里到底发生了什么(因为有 Objective-C 代码)。

因此,解决方案是创建一个自定义的BarButtonItem 而不是返回BarButtonItem,并在 NavigationVC 中的每个 VC 中添加这个按钮,你需要这个按钮。

这是您必须在每个 VC 中添加的代码:

override func viewDidLoad() {
    super.viewDidLoad()

    //some other code

    self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "backButtonIcon"), style: UIBarButtonItem.Style.plain, target: self, action: #selector(backButtonPressed))
}

@objc func backButtonPressed() {

    // implement your action here
}
于 2018-11-16T11:50:25.033 回答