近期研发一个功能需要将字符串写到MacOS系统剪贴板中,从而粘贴分享,研发过程中踩了一个小坑,所以把Swift读写MacOS系统剪贴板的方法总结出来,以便其他人遇到时能顺利趟过。
首先,如果需要读取系统剪贴板中的字符串内容,非常简单,如下示例即可实现:
let ss = NSPasteboard.generalPasteboard().stringForType(NSStringPboardType)
print(ss)
其中:
class func generalPasteboard() -> NSPasteboard
Returns the general NSPasteboard object.
func stringForType(_ dataType: String) -> String?
Returns a concatenation of the strings for the specified type from all the items in the receiver that contain the type.
public let NSStringPboardType: String // Use NSPasteboardTypeString
其次,如果按照上面的逻辑要将字符串写入系统剪贴板中,我们很容易想到如下代码:
let b = NSPasteboard.generalPasteboard().setString("This is a test string.", forType: NSStringPboardType)
print(b)
然而,运行上述代码会发现,setString返回值b为false,同时,使用系统剪贴板也无法粘贴出相应的字符串。
要解决该问题,需要调整代码如下:
let pasteboard = NSPasteboard.generalPasteboard()
pasteboard.declareTypes([NSStringPboardType], owner: nil)
let b = pasteboard.setString("This is a test string.", forType: NSStringPboardType)
print(b)
其中
func declareTypes(_ newTypes: [String], owner newOwner: AnyObject?) -> Int
Prepares the receiver for a change in its contents by declaring the new types of data it will contain and a new owner.
现在再次运行,返回值b为true,同时,使用command+v可以在其他编辑器中粘贴出"This is a test string."
以上内容给出了使用Swift访问MacOS系统剪贴板的简单方法,希望能够帮助读者解决问题,也欢迎提出问题和建议。
![](https://img.haomeiwen.com/i2166372/cf8b69bb1f192593.png)
网友评论