xcode 如何将 textField 复制到 OSX 剪贴板?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3655038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to copy textField to OSX clipboard?
提问by 0SX
I'm stuck here. I know how to copy and paste on the iPhone side of things but how can I copy contents from a textField to the global clipboard in OSX. I've been searching the web but there are really no examples. So let me explain in detail what I'm trying to accomplish. I have a NSTextField named helloField and I want to be able to copy the contents of this helloField to the global pasteboard by pressing a button. How can this be done and is there certain libraries I need? Thanks.
我被困在这里。我知道如何在 iPhone 端复制和粘贴东西,但如何将内容从 textField 复制到 OSX 中的全局剪贴板。我一直在网上搜索,但真的没有例子。所以让我详细解释一下我要完成的任务。我有一个名为 helloField 的 NSTextField,我希望能够通过按下按钮将这个 helloField 的内容复制到全局粘贴板。如何做到这一点,我需要某些库吗?谢谢。
回答by erkanyildiz
On iOS
在 iOS 上
[UIPasteboard generalPasteboard].string = helloField.text;
On OSX
在 OSX 上
[[NSPasteboard generalPasteboard] clearContents];
[[NSPasteboard generalPasteboard] setString:helloField.stringValue forType:NSStringPboardType];
On macOS and Swift 3.x
在 macOS 和 Swift 3.x 上
let pasteBoard = NSPasteboard.general()
pasteBoard.clearContents()
pasteBoard.writeObjects([text as NSString])
回答by Sheamus
Code to copy a string to the clipboard:
将字符串复制到剪贴板的代码:
[[NSPasteboard generalPasteboard] clearContents];
[[NSPasteboard generalPasteboard] setString:copiedString forType:NSPasteboardTypeString];
NSStringPboardType
is deprecated. There's a note in NSPasteboard.h
about pboard
types:
NSStringPboardType
已弃用。NSPasteboard.h
关于pboard
类型有一个注释:
Use of pboard types should be replaced with use of UTIs. Pboard types will be deprecated in a future release.
应使用 UTI 代替使用 pboard 类型。Pboard 类型将在未来版本中弃用。
Also in the header file:
同样在头文件中:
APPKIT_EXTERN NSString *const NSPasteboardTypeString NS_AVAILABLE_MAC(10_6); // Replaces NSStringPboardType
...
APPKIT_EXTERN NSString *NSStringPboardType; //Use NSPasteboardTypeString
APPKIT_EXTERN NSString *const NSPasteboardTypeString NS_AVAILABLE_MAC(10_6); // 替换 NSStringPboardType
...
APPKIT_EXTERN NSString *NSStringPboardType; //使用 NSPasteboardTypeString
回答by Pier
For Cocoa macOS in Swift 3:
对于 Swift 3 中的 Cocoa macOS:
let pasteBoard = NSPasteboard.general()
pasteBoard.clearContents()
pasteBoard.setString("something", forType: NSPasteboardTypeString)