我有一个具有播放/暂停功能的音频播放器按钮。
@IBAction func playPauseButton(_ sender: UIButton) {
let playBtn = sender
if buttonState == 1 {
audioPlayer.play()
buttonState = 2
playBtn.setImage(UIImage(named:"pause.png"),for:UIControl.State.init())
} else {
audioPlayer.pause()
buttonState = 1
playBtn.setImage(UIImage(named:"play.png"),for:UIControl.State.init())
}
}
和AVPlayer的didLoad中的观察者:
audioPlayer.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil)
如何在观察功能中更改按钮的图像:
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "rate" {
if audioPlayer.rate > 0.0 {
print("audio started")
// change button image in "pause"
} else {
print("audio paused")
// change button image in "play"
}
}
}
@IBOutlet var yourButton: UIButton!
@IBAction func playPauseButton(_ sender: UIButton) { }
然后在您的代码的后面,您可以引用这样的按钮,它将图像更改为您选择的UIImage
。
yourButton.setImage(image: yourImage, for state: .normal)