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

时间:2017-01-03 21:43:55

标签: swift macos swift3 nspasteboard

我是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)
       }
    }        
}

5 个答案:

答案 0 :(得分:16)

适用于 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

答案 1 :(得分:5)

时代变了。在Swift 3+中,您可以这样做:(如果您只对字符串感兴趣)

[Fact]
public void GetUserNames_ValidRequest_ShouldReturnOk()
{
    _repository
        .Setup(r => r.GetUsers())
        .Return(new List<User> 
            {
                new User { Name = "SomeRandomName" },
                new User { Name = "SomeRandomName2" }  
            });

    var result = _controller.GetUserNames();

    result.Should().BeOfType<OkObjectResult>();
    // Code to check if 2 names are returned
}

答案 2 :(得分:2)

另一个Swift 4解决方案

// 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)

答案 3 :(得分:0)

另一种解决方案。

class ViewController : NSViewController {

  @IBAction func pasteMenuItemAction(_ sender: NSMenuItem) {
    let p = NSPasteboard.general
    let x = p.readObjects(forClasses: [NSString.self], options: nil)
    let s = x as! [NSString]
    if 0 < s.count {
      print(s[0])
    }
  }

}

该func pasteMenuItemAction()绑定到编辑&gt;粘贴菜单项。

我使用writeObjects()进行编辑&gt;复制。所以我很自然地在这里使用它的对应readObjects()

使用Xcode 9.2,Swift 4确认

<强>加了:

编辑&gt;的解决方案之一复制:

  @IBAction func copyMenuItemAction(_ sender: NSMenuItem) {
    let t = "Hello!"
    let p = NSPasteboard.general
    p.clearContents()
    p.writeObjects([t as NSPasteboardWriting])
  }

该func copyMenuItemAction()绑定到编辑&gt;复制菜单项。

答案 4 :(得分:-1)

更轻松✅快速4:

@IBAction func pasteAction(_ sender: Any) {
    guard let stringToPaste: String = UIPasteboard.general.items.last?.first?.value as? String else { return }
    MYTEXTVIEW.text = stringToPaste
}