MMV MMV - 10 months ago 89
Swift Question

Copy NSTableView row greyed out

I would like to add copy (Command + C) functionality to my NSTableView for a row (or multiple rows) that the user has selected. Based on what I read the copy functionality in the Menu Item should be active automatically if you implement copy in your TableView Controller Delegate.

I've tried adding in the NSTableViewController (is the delegate and data source of the table view) the following things with no luck, the copy menu item still appears greyed out:

  1. override func copy() -> AnyObject {
    print("TEST: copytriggered") /Here i would copy to clipboard the selected rows/
    return true

Conforming to NSCopying, implementing copyWithZone...

Trying 1 and 2 in the window controller and app delegate.

  1. Adding func tableView(_ tableView: NSTableView,
    pasteboardWriterForRow row: Int) -> NSPasteboardWriting? in the TableView data source.

I have no clue what to do at this point, any help appreciated.



Answer Source

Just got the answer, publishing here for future reference.

You are confusing the Copy edit action method with the methods for making a duplicate of an object. The NSCopying protocol and the copyWithZone() method are for the latter, enabling an object to create a copy of itself. Likewise, the copy() method is just a convenience cover method for copyWithZone().

The action method for the Copy edit menu item is subtly different. It's "func copy(_ sender: AnyObject?)". That's the general form for all action methods, taking a sender argument and not returning anything. You need to implement that method.

Finally, tableView(_:pasteboardWriterForRow:) is generally only used for drag-and-drop, when the user drags a row.