如何使用@IBAction函数和观察者更改按钮上的图像

问题描述 投票:1回答:1

我有一个具有播放/暂停功能的音频播放器按钮。

@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"
            }
        }
    } 
ios swift xcode ibaction
1个回答
0
投票
示例:

@IBOutlet var yourButton: UIButton! @IBAction func playPauseButton(_ sender: UIButton) { }

然后在您的代码的后面,您可以引用这样的按钮,它将图像更改为您选择的UIImage

yourButton.setImage(image: yourImage, for state: .normal)

© www.soinside.com 2019 - 2024. All rights reserved.