当前位置 : 主页 > 手机开发 > 其它 >

在macOS上使用Swift 3从剪贴板中读取

来源:互联网 收集:自由互联 发布时间:2021-06-11
我是 Swift的初学者,我正在试图弄清楚如何在macOS(Swift 3)上阅读已复制到剪贴板的内容?我经常搜索,但似乎找不到任何有用的东西. 我在网上试过的一些事情: var pasteboardItems: [NSPasteboa
我是 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
网友评论