Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
                        }
like image 578
Paul Avatar asked Nov 19 '25 21:11

Paul


1 Answers

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)
    }
}
like image 166
workingdog support Ukraine Avatar answered Nov 21 '25 11:11

workingdog support Ukraine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!