Change image when clicking a button in SwiftUI


In this SwiftUI tutorial, you will see how to change an image when clicking on a button.

To achieve our task, we will actually create a string that contains the image name. Tapping the button will change the string value. That value will be used in the Image instance.

Before describing it in detail, let’s first create our string imageName with the @State property so that we can change it dynamically.

@State private var imageName = "myimage"

Now let’s place an image using the SwiftUI Image instance in Xcode:

    Image(imageName)
        .resizable()
        .aspectRatio(contentMode: .fit)

Now let’s create our button and change the imageName string in the button action:

    Button(action: {
        self.imageName = "anotherimage"
    }, label: {
        Text("Change the image")
    })

Complete code for changing the SwiftUI image on button tap

Now let’s see the complete code that will change the image when tapping the button in SwiftUI:

    @State private var imageName = "myimage"
   
    var body: some View {

        VStack {
              
            Image(imageName)
                .resizable()
                .aspectRatio(contentMode: .fit)
            
            
            Button(action: {
                self.imageName = "anotherimage"
            }, label: {
                Text("Change the image")
            })
        
    }
}

Now let me explain the complete code…

We have started by creating a string variable imageName and assigning the image asset name myimage. Next, we added an image and pass the imageName string to display our image in the app.

After that, we created a button. Inside the button action, we have added a code block where we are changing the imageName string from myimage to anotherimage. Below is the code:

self.imageName = "anotherimage"

The above line of code is actually changing our old image to a new image. This piece of code is playing the key role to accomplish the task.

When we click the button, the imageName string changes and it also changes the image. This is because we are using the string variable name in the Image instance.

Thus we are able to change the SwiftUI image when tapping the button.