Reading time: 1 min

This quick recipe shows how to paste an image into your SwiftUI app using PasteButton.

The end result looks like this:

preview

PasteButton is available starting with SwiftUI 3 (iOS 15, macOS 12).

The trick is to use UTType.image, and then load the image data from NSItemProvider, just like you do with drag & drop.

Here's the full code:

import SwiftUI
import UniformTypeIdentifiers

struct PasteButtonTest: View {
  @State private var image: UIImage?

  var body: some View {
    VStack {
      Image(uiImage: image ?? .init())

      PasteButton(supportedContentTypes: [UTType.image]) { info in
        for item in info {
          item.loadObject(ofClass: UIImage.self) { item, error in
            if let img = item as? UIImage {
              image = img
            }
          }
        }
      }
      .buttonBorderShape(.capsule)
    }
    .padding()
  }
}

Next Post Previous Post