Reading from the clipboard with Swift 3 on macOS

前端 未结 5 1882
轮回少年
轮回少年 2021-02-07 14:44

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 a

5条回答
  •  星月不相逢
    2021-02-07 15:13

    Works for Swift 3 and 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
    

提交回复
热议问题