How to allow Paste (cmd+v) into NSTableView cell?

708 views Asked by At

I've implemented copying tableView selected cell value by shortcut cmd+C. Now I was trying to implement the pasting cmd+V. When I click on tableView cell, it gets selected. Another click, I'm editing it. While editing, I press cmd+V and nothing happens. I can write text but can't insert by copy-pasting.

Tried to implement it manually via Edit menu -> Paste Cmd+V.

    @IBAction func onPaste(_ sender: Any) {
      let pasteBoard = NSPasteboard.general
      pasteBoard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
      tableView.selectedCell().set??? = pasteBoard.string(forType: NSPasteboard.PasteboardType.string)
    }

But don't know how to set a value on NSCell.

3

There are 3 answers

2
Clegrand On

To allow paste on TextField, create custom TextField class by extending NSTextField :

class EditingTextField: NSTextField {

  private let commandKey = NSEventModifierFlags.command.rawValue
  private let commandShiftKey = NSEventModifierFlags.command.rawValue | NSEventModifierFlags.shift.rawValue

  override func performKeyEquivalent(with event: NSEvent) -> Bool {
    if event.type == NSEventType.keyDown {
      if (event.modifierFlags.rawValue & NSEventModifierFlags.deviceIndependentFlagsMask.rawValue) == commandKey {
        switch event.charactersIgnoringModifiers! {
        case "x":
          if NSApp.sendAction(#selector(NSText.cut(_:)), to:nil, from:self) { return true }
        case "c":
          if NSApp.sendAction(#selector(NSText.copy(_:)), to:nil, from:self) { return true }
        case "v":
          if NSApp.sendAction(#selector(NSText.paste(_:)), to:nil, from:self) { return true }
        case "z":
          if NSApp.sendAction(Selector(("undo:")), to:nil, from:self) { return true }
        case "a":
          if NSApp.sendAction(#selector(NSResponder.selectAll(_:)), to:nil, from:self) { return true }
        default:
          break
        }
      }
      else if (event.modifierFlags.rawValue & NSEventModifierFlags.deviceIndependentFlagsMask.rawValue) == commandShiftKey {
        if event.charactersIgnoringModifiers == "Z" {
          if NSApp.sendAction(Selector(("redo:")), to:nil, from:self) { return true }
        }
      }
    }
    return super.performKeyEquivalent(with: event)
  }
}
0
Vito Valov On

My mistake. I haven't payed attention that when I change the Edit Menu action, it removes the default behavior. Since I changed the default action to call my custom method, the :paste action was disconnected from cmd+v shortcut.

0
Ronald Hofmann On

I had the same problem with my app and found, it´s pretty easy to solve.

It is always possible to copy and paste to a NSTextField using the mouse context menu. Copy and paste using the keyboard with cmd-c and cmd-v is automatically available when an edit menu is available.

I added an Edit Menu item which I had removed before and copy paste was immediately available.