Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Add an Image to a Button in SwiftUI
Written by Team Kodeco

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.
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.
You can use an Image view inside a Button view in SwiftUI.

Here’s how this code works:

  • Button(action: { }) { } creates a new button. The action closure contains code that will run when the button is pressed. In this case, the closure is empty, so nothing will happen when the button is pressed.

  • Image("AvocadoFriend") sets the content (or label) of the button to be an image. The argument is the name of the image resource, which is expected to be included in the app’s assets.

  • .resizable() is a modifier that makes the image resizable, meaning that it can be stretched or shrunk to fit its frame.

  • .frame(width: 100, height: 100) is a modifier that sets the size of the image’s frame to be 100 by 100 points. Because the image is resizable, it will be scaled to fit this frame.

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.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.