How can I respond to an image being pasted while a TextField has focus?

82 views Asked by At

In my app, I'd like to let users paste images from the clipboard into my app's content while a TextField has focus. When an image is pasted, it'll be added as an attachment to the associated item the TextField is in.

I've tried several things. The first are using the .pasteDestination and .onPasteCommand view modifiers.


import SwiftUI

struct ContentView: View {
    @State var text = ""

    var body: some View {
        VStack {
            TextField("", text: $text)
                .pasteDestination(for: Image.self, action: { images in
                    print("Pasted \(images.count) images")
                })
                .onPasteCommand(of: [.image]) { images in
                    print("paste command: \(images.count) images")
                }
        }
        .padding()
    }
}

With an image from Preview in the clipboard, nothing ever gets printed while the TextField has focus. I have confirmed the same code works when applied to something .focusable() that has focus. This is specific to TextField.

The second approach I tried is overriding the .pasteboard commands.


import SwiftUI

@main
struct PasteImageApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .commands {
            CommandGroup(replacing: .pasteboard) {
                Button("Paste") {
                    print("Pasting something...")
                    let pasteboardType = NSPasteboard.PasteboardType.png
                    if let imageData = NSPasteboard.general.data(forType: pasteboardType) {
                        print("Read png data of length \(imageData.count)")
                    }
                }
                .keyboardShortcut("V")
            }
        }
    }
}

That lets me paste an image, but ruins all the default behavior in the TextField, so I can't paste text.

Is there any way to do this in SwiftUI?

0

There are 0 answers