swift - 我如何在另一个类中使用此扩展委托(delegate)更新我的 ViewController UI

标签 swift class delegates avfoundation

我正在使用一个名为 AudioManager 的类,您可以找到它作为这个问题的答案 here .

它有委托(delegate)方法 AVAudioPlayerDelegate 作为 AudioManager 类的扩展。

有没有办法在我的 View Controller 中使用它或覆盖这些委托(delegate)方法,以便能够更改我的 UI 中的属性。 这是扩展名:

extension AudioManager: AVAudioPlayerDelegate {

   func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, 
 successfully flag: Bool) {

       player.stop()

       print("Finish Playing")

   }

   func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, 
error: Error?) {

        print(/error?.localizedDescription)

    }

}

这是我的 View Controller 播放按钮代码:

@IBAction func playButtonTapped(_ sender: UIButton) {
    if AudioManager.shared.player == nil {
        if recordFilePath != nil {
            AudioManager.shared.setupPlayer(URL(string:recordFilePath)!)
        }
    }

    if playButtonIsChecked {
        playButtonIsChecked = false
        AudioManager.shared.player?.play()
        playRecordButton.setBackgroundImage(#imageLiteral(resourceName: "pauseProfileButton"), for: .normal)
    } else {
        playRecordButton.setBackgroundImage(#imageLiteral(resourceName: "editProfilePlay"), for: .normal)
        playButtonIsChecked = true
        AudioManager.shared.player?.stop()

    }

上面的代码很好,当我调用 player?.stop() 时,AVAudioPlayerDelegate 方法是从 AudioManager 类调用的,但是当音频文件结束并在我没有调用 player?.stop 的情况下停止时,按钮背景图像当然不会改变。

我如何在我的 View Controller 中使用这个委托(delegate)方法并知道我的音频文件何时结束和停止。

最佳答案

在您的 AudioManager 类中,您可以实现回调(闭包),例如:

var isAudioStopped: ((Bool) -> Void)?

您可以在您的扩展中调用它,在委托(delegate)方法中:

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, 

成功标记:Bool) {

   player.stop()
   isAudioStopped?(true)

   print("Finish Playing")

然后在您的 ViewController 方法中:

AudioManager.shared.isAudioStopped = {
    [weak self] completion in 
    // if completion the audio is stopped 
}

关于swift - 我如何在另一个类中使用此扩展委托(delegate)更新我的 ViewController UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46856881/

相关文章:

ios - 使用嵌入在动态框架中的第三方框架

c++ - 如何删除由 OpenGL 绘制的 C++ 对象?

arrays - Lua 表和类之间有什么区别?

c# - 创建调用方法的表达式树

ios - Swift 中来自两个不同 JSON 的数据放入同一结构中

ios - 如何从自定义 TableViewCell 访问 ViewController 的 navigationController

ios - Swift 中缺少参数错误的参数

python - 无法在Python中使用外部函数更改类变量

c# - C# observer/observable with delegates 的 super 简单示例

c# - 将 MethodInfo 连接到委托(delegate)字段 (FieldInfo)