我必须确保当输入字段出现时,将剪贴板上的文本作为输入字段的文本插入,如果它满足特定条件。
为此,我在输入字段上使用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
文本:(在运行应用程序之前,使用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)
}
}