How to add image to Xcode project in SwiftUI

In this introductory tutorial you’re going to learn how to add images to SwiftUI Xcode project and use them in your SwiftUI code.

First of all, you need to have an image available on your Mac which you’d like to use in your SwiftUI app. If you don’t have one, feel free to download it from Unsplash. After downloading, I re-named it to “fall-leaves.jpg”. (Full image credit to Ricardo Gomez Angel).

Open Xcode’s Asset Catalog

Click on Assets.xcassets in project navigator to open the assets catalog for your project.

Xcode's Assets.xcassets
Xcode’s Assets.xcassets

Add Image

There are two ways to add an image to Xcode project. 

First one is to drag and drop an image file from Finder onto the assets catalog. Dragging the image will automatically create new image set for you.

Drag and drop image onto Xcode's assets catalog.
Drag and drop image onto Xcode’s assets catalog.

Or, click on a plus button at the very bottom of the Assets navigator view and then select “New Image Set”.

New Image Set
New Image Set

After that, drag and drop an image into the newly create Image Set, placing it at appropriate 1x, 2x or 3x slot. For testing purposes you can only drag it onto the 1x slot.

Re-naming image asset
Re-naming image asset

Make sure to double click on the newly created Image Set and re-name it according to your needs. I’m going to name mine “fall-leaves”

Use Image in SwiftUI

import SwiftUI

struct ContentView: View {
    var body: some View {
        Image("fall-leaves")
            .resizable()
            .scaledToFit()
    }
}

Take a look at the result below.

Using image in SwiftUI
Using image in SwiftUI

Related tutorials: