在macOS上使用Swift 3从剪贴板中读取 [英] Reading from the clipboard with Swift 3 on macOS
本文介绍了在macOS上使用Swift 3从剪贴板中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Swift的初学者,我试图弄清楚如何阅读在macOS(Swift 3)上复制到剪贴板的内容?我进行了很多搜索,但似乎找不到任何有效的方法.
I'm a beginner with Swift, and I'm trying to figure out how can I read what has been copied to the clipboard On macOS (Swift 3)? I've searched a lot but can't seem to find anything that works.
我从网上尝试过的一些方法:
A few of the things I've tried from online:
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
这篇关于在macOS上使用Swift 3从剪贴板中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文