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:
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:
Here’s how this code works:
-
Button(action: { }) { }
creates a new button. Theaction
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.