47 - Add an Image to a Button in SwiftUI

Buttons are an essential part of any user interface, and adding images to buttons can often make them more appealing and easier to understand. In SwiftUI, you can easily add images to buttons by using the Image view.

To add an image to a button, you need to create an instance of the Image view and pass it as the label for the button. Here’s the friendly fruit used in the following example:

Download this image and add it to your project's assets.

struct ContentView: View {
  var body: some View {
    Button(action: {
      // action to perform when the button is tapped
    }) {
      Image("AvocadoFriend")
        .resizable() // This allows the image to be resized
        .frame(width: 100, height: 100) // This sets the size of the image
    }
  }
}

Your preview should look like this:

You can use an Image view inside a Button view in SwiftUI.

Here’s how this code works:

In summary, this ContentView displays a button with an image named “AvocadoFriend” that is 100 by 100 points in size. The image will be resized to fit the frame if it is not already that size. Currently, the button does nothing when pressed, but you can add functionality by adding code to the action closure.