【发布时间】:2016-09-11 16:22:06
【问题描述】:
我希望用户按下一个按钮,它会更改背景颜色(变为黄色),播放 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)
}
【问题讨论】: