We often may need to use an image as the button. For example, if you want to let a user upload some files to the cloud, then you may want an icon something like given below:
So in this tutorial, I am going to show you how to use an image as the SwiftUI button. This type of button is known as the image button. Tapping the image will act as tapping the button.
In our example, we are going to use the cloud upload image I have mentioned above.
Let’s open our assets directory, then drag and drop our image. After that, we can use it in our app.
Now let’s create our button just like any other button using the built-in SwiftUI Button control. To use the image for the button instead of using label text, we will use the Image View in the label of the button. Below is how to do it:
Button(action: {
print("Image Button Tapped...")
}, label: {
Image("upload-icon")
})
If we run it, we will able to see the image:
To verify if our image starts acting like a button, just tap on it. If you see the message Image Button Tapped...
in the terminal, it is confirmed that our image is now a button.
We can also set the width and height of our image and the image also will automatically adjust:
Button(action: {
print("Image Button Tapped...")
}, label: {
Image("upload-icon")
.resizable()
.frame(width: 96.0, height: 96.0)
})
You may need to change the height and width as you can see in the above code to change the size of your button. The size of the button will adjust with the change in the image size.