Search code examples
iosswiftxcodeibaction

How to change image on button with @IBAction function and an observer


I have a button for audio player with function Play/Pause.

@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())
           }
}

and observer in didLoad for AVPlayer:

audioPlayer.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil)

How to change image for button in OBSERVE FUNCTION:

    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"
            }
        }
    } 

Solution

  • You can reference the button by adding an IBOutlet. You create this by ctrl-dragging from the storyboard to the view controller code, in the same way you did for the IBAction.

    An IBOutlet provides a variable to reference the button (or other storyboard view). An IBAction triggers a function when the view is interacted with.

    Example:

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

    Then later in your code you can refer to the button like this, which changes the image to a UIImage of your choice.

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