Paul
Paul

Reputation: 4430

MacOS swiftUI copy the text from the clipboard into a TextField field

I have to make sure that when the input field appears, to take the text that is on the clipboard and insert it as the text of the input field if it meets specific conditions.

For this I am using onAppear on the input field, the problem is how to get the text.

Can anyone help me out?

                    TextField("Git Repository URL", text: $repoUrlStr)
                        .lineLimit(1)
                        .padding(.bottom, 15)
                        .frame(width: 300)
                        .onAppear {
                            // Write to pasteboard
                            let pasteboard = NSPasteboard.general
                            pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
                            //pasteboard.setString("Good Morning", forType: NSPasteboard.PasteboardType.string)

                            // Read from pasteboard
                            let read = pasteboard.pasteboardItems?.first?.string(forType: .string)
                            print("ok", read)
                        }

Upvotes: 2

Views: 2463

Answers (1)

try this approach, to show what you read from the Pasteboard into the TextField text: (use cmd+c to copy some text into the pasteboard before you run the app)

struct ContentView: View {
    @State var repoUrlStr = ""
    
    var body: some View {
        TextField("Git Repository URL", text: $repoUrlStr)
            .lineLimit(1)
            .padding(.bottom, 15)
            .frame(width: 300)
            .onAppear {
                if let read = NSPasteboard.general.string(forType: .string) {
                    repoUrlStr = read  // <-- here
                }
            }.frame(width: 444, height: 444)
    }
}

Upvotes: 2

Related Questions