coiai Logo

This article is an English translation of the original Japanese post. Read the Japanese original →

[SwiftUI] Adding, Previewing, and Deleting Images

December 18, 2023

Categories: SwiftUI

Hi there! Today I built a feature for selecting images in SwiftUI. It looks like the video below.

The file is called SelectImage.swift.

Overview of the code

import SwiftUI
import UniformTypeIdentifiers

struct SelectImage: View {
    @Binding var image: NSImage?
    @State private var isHovering = false

    var body: some View {
        // Various code goes here
    }
}

First, we import the libraries we need with import SwiftUI and import UniformTypeIdentifiers. Then we create a view named SelectImage. This view has two variables: @Binding var image: NSImage?, which holds the selected image, and @State private var isHovering = false, which tracks whether the mouse is hovering over the image.

Selecting an image

Button("Select Image") {
    let panel = NSOpenPanel()
    panel.allowedContentTypes = [UTType.image]
    panel.allowsMultipleSelection = false
    if panel.runModal() == .OK {
        let url = panel.url
        self.image = NSImage(contentsOf: url!)
    }
}

We create a “Select Image” button. Clicking it opens a file picker dialog, and whatever image you choose is stored in the image variable as an NSImage.

Displaying the image

if let img = image {
    ZStack {
        Rectangle()
            .fill(Color.gray)
            .frame(width: 44, height: 44)
            .cornerRadius(4)
        Image(nsImage: img)
            .resizable()
            .scaledToFit()
            .frame(width: 40, height: 40)
    }
}

The selected image is displayed inside a square frame, and it's automatically resized to fit within that frame.

Deleting the image

Button {
    self.image = nil
} label: {
    Image(systemName: "xmark.circle")
        .foregroundColor(.white)
        .font(.system(size: 16, weight: .bold))
}
.disabled(image == nil)
.padding(2)
.background(Color.black)
.clipShape(Circle())
.opacity(isHovering ? 0.9 : 0)
.onHover { hovering in
    isHovering = hovering
}

Hovering the mouse over the image reveals a delete button. Pressing it clears the selected image.

Wrap-up

That covers the SelectImage.swift code I put together. With this, you can easily add image-picking functionality to a SwiftUI app. Give it a try yourself! See you next time!

[SwiftUI] Adding, Previewing, and Deleting Images | coiai Inc.