MacOS swiftUI 将剪贴板中的文本复制到 TextField 字段中

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

我必须确保当输入字段出现时,如果符合特定条件,则将剪贴板上的文本作为输入字段的文本插入。

为此,我在输入字段上使用 onAppear,问题是如何获取文本。

谁能帮帮我?

                    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)
                        }

尝试这种方法,将您从 Pasteboard 中读取的内容显示到 TextField 文本中:(在 [=16= 之前使用 cmd+c 将一些文本复制到粘贴板中] 应用)

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)
    }
}