NSTextView在粘贴之前修改字符串

时间:2018-12-11 17:49:05

标签: macos nstextview nspasteboard

我的目标是修改字符串-删除所有非字母(数字,空格等)-然后再将其粘贴到NSTextView中。

通过此link,我想到了以下代码:

override func paste(_ sender: Any?) {
    let pasteboard = NSPasteboard.general
 // receive string from pasteboard
    if let pasteboardString = pasteboard.string(forType: .string) {
        let lettersOnly = CharacterSet.letters

     // filter the incoming string
        let lettersOnlyString = String(pasteboardString.unicodeScalars.filter { lettersOnly.contains($0) })

     // put back filtered string into pasteboard
        pasteboard.setString(lettersOnlyString, forType: .string)
        super.paste(sender)

     // put back initial formatted string
        pasteboard.setString(pasteboardString, forType: .string)
    }
}

lettersOnlyString的确是修改后的字符串,但无论如何最后还是粘贴了原始字符串,我仍然看到所有非字母字符。

我在这里想念的是什么,也许这不是走的路?也许我需要为此重写另一种方法?

1 个答案:

答案 0 :(得分:0)

我想我找到了答案,我必须在pasteboard.clearContents()之前添加pasteboard.setString

为了完整起见,这是工作代码:

override func paste(_ sender: Any?) {
    let pasteboard = NSPasteboard.general

// get string from pasteboard
    if let pasteboardString = pasteboard.string(forType: .string) {
     // remove formatting from string
        let lettersOnly = CharacterSet.letters
        let lettersOnlyString = String(pasteboardString.unicodeScalars.filter { lettersOnly.contains($0) })

     // put modified string on pasteboard
        pasteboard.clearContents()
        pasteboard.setString(lettersOnlyString, forType: .string)

     // paste string from pasteboard as plain text
        pasteAsPlainText(sender)

     // put original string back on pasteboard
        pasteboard.clearContents()
        pasteboard.setString(pasteboardString, forType: .string)
    }
}

更新:

它甚至可以更轻松地完成:

override func paste(_: Any?) {
    let pasteboard = NSPasteboard.general
    guard let pasteboardString = pasteboard.string(forType: .string),
        let validatedInput = validateInput(pasteboardString)
    else { return }

    insertText(validatedInput, replacementRange: NSMakeRange(NSNotFound, 0))
}

其中validateInput()是用于过滤输入字符串的重构函数。