Toggle between play and pause icon images in SwiftUI


In music or video player apps, you can notice that the play icon changes into the pause and the pause icon image change into a play icon when you click the button to play or pause the video or the music.

In this tutorial, you will see the effective way to change the play and pause icon image when you click the button. This tutorial is simply focused to let you know how to toggle between the play and pause icon images of the button in SwiftUI.

In Swift programming, there is a method toggle() that can be used to toggle any boolean variable’s value. If the boolean value is true, then it will change it into false and if it is false then the method will change it to true.

Now we are going to use the Swift toggle() method to toggle the play pause icon by changing the boolean value of a variable. We will use the SwiftUI Button control which has the icon play or pause.

Let’s look at our code below:


    @State private var isPlaying = false

    var body: some View {
        
        
        Button(action: {
            self.isPlaying.toggle()
        }, label: {
            Image(systemName: self.isPlaying ? "pause" : "play")
        })
        
          
   }
    

In the above program, we have taken a state variable isPlaying and assigned a boolean value false. In the view, we have created a SwiftUI button with the icon image as the label.

Inside the Image, we are checking a condition, if isPlaying has the value false, it will show the pause icon. In case of isPlaying is true, it will show the play icon:

Image(systemName: self.isPlaying ? "pause" : "play")

In the button action, we are using the toggle() method to toggle the value of isPlaying:

self.isPlaying.toggle()

When the value of isPlaying changes, the icon of the button also changes as we are using the value in the Image view.