我是 Swift 的初学者,我想知道如何在 macOS (Swift 3) 上读取已复制到剪贴板的内容?我搜索了很多,但似乎找不到任何有用的东西。
我从网上尝试过的一些东西:
var pasteboardItems: [NSPasteboardItem]? { get }
print("\(pasteboardItems)")
和
let pb = NSPasteboard.general()
pb.string(forType: NSPasteboardTypeString)
print("\(pb)")
和
let pasteboard = UIPasteboard.general
if let string = pasteboard.string {
// text was found and placed in the "string" constant
}
最后
func paste(sender: AnyObject?) {
let pasteboard = NSPasteboard.generalPasteboard()
if let nofElements = pasteboard.pasteboardItems?.count {
if nofElements > 0 {
// Assume they are strings
var strArr: Array<String> = []
for element in pasteboard.pasteboardItems! {
if let str = element.stringForType("public.utf8-plain-text") {
strArr.append(str)
}
}
// Exit if no string was read
if strArr.count == 0 { return }
// Perform the paste operation
dataSource.cmdPaste(strArr)
}
}
}
最佳答案
适用于 Swift 3 和 Swift 4
// Set string to clipboard
let pasteboard = NSPasteboard.general
pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
pasteboard.setString("Good Morning", forType: NSPasteboard.PasteboardType.string)
var clipboardItems: [String] = []
for element in pasteboard.pasteboardItems! {
if let str = element.string(forType: NSPasteboard.PasteboardType(rawValue: "public.utf8-plain-text")) {
clipboardItems.append(str)
}
}
// Access the item in the clipboard
let firstClipboardItem = clipboardItems[0] // Good Morning
关于swift - 在 macOS 上使用 Swift 3 从剪贴板读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41452868/