gpt4 book ai didi

Swift - 按下按钮(完成处理程序问题)

转载 作者:行者123 更新时间:2023-11-28 11:03:52 25 4
gpt4 key购买 nike

我希望用户按下一个按钮,它会改变背景颜色(黄色),播放 WAV 并在完成 WAV 后按钮恢复到其原始颜色(红色)。所以在声音周围有一个完成处理程序。尝试了以下代码的各种组合,但 WAV 播放并且按钮似乎没有改变颜色。

这是错误的方法还是我做错了什么?不想在颜色变化周围放置完成处理程序,因为我认为这太过分了。

非常感谢。

typealias CompletionHandler = (success:Bool) -> Void

@IBAction func fireButton(sender: AnyObject) {
playLaser( { (success)-> Void in
if success {
self.shots -= 1
self.labelShotsLeft.text = String(self.shots)
} else {

}
})
}

func playLaser(completionHandler: CompletionHandler) {
fireButton.layer.backgroundColor = UIColor.yellowColor().CGColor
let url = NSBundle.mainBundle().URLForResource("laser", withExtension: "wav")!
do {
player = try AVAudioPlayer(contentsOfURL: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}
self.fireButton.layer.backgroundColor = UIColor.redColor().CGColor
completionHandler(success: true)
}

最佳答案

要检测AVAudioPlayer播放完毕,需要使用AVAudioPlayerDelegate

你可能需要这样写:

func playLaser(completionHandler: CompletionHandler) {
fireButton.layer.backgroundColor = UIColor.yellowColor().CGColor
let url = NSBundle.mainBundle().URLForResource("laser", withExtension: "wav")!
do {
player = try AVAudioPlayer(contentsOfURL: url)
guard let player = player else { return }
player.delegate = self //<- Sorry, this was missing in my first post
player.play()
} catch let error as NSError {
print(error.description)
}
audioPlayerCompletionHandler = completionHandler
}

var audioPlayerCompletionHandler: CompletionHandler?
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
self.fireButton.layer.backgroundColor = UIColor.redColor().CGColor
audioPlayerCompletionHandler?(success: true)
}

(您需要将对 AVAudioPlayerDelegate 的一致性添加到 ViewController 的声明 header 中。)

关于Swift - 按下按钮(完成处理程序问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39438186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com