Search code examples
macosdrag-and-dropnstableview

Drag & Drop Reorder Rows on NSTableView


I was just wondering if there was an easy way to set an NSTableView to allow it to reorder its rows without writing any pasteboard code. I only need it to be able to do this internally, within one table. I have no issue writing the pboard code, except that I'm fairly sure that I saw Interface Builder have a toggle for this somewhere / saw it working by default. It certainly seems like a common enough task.

Thanks


Solution

  • If you take a look at the tool tip in IB you'll see that the option you refer to

    - (BOOL)allowsColumnReordering
    

    controls, well, column reordering. I do not believe there is any other way to do this other than the standard drag-and-drop API for table views.

    EDIT: ( 2012-11-25 )

    The answer refers to drag-and-drop reordering of NSTableViewColumns; and while it was the accepted answer at the time. It does not appear, now nearly 3 years on, to be correct. In service of making the information useful to searchers, I'll attempt to give the more correct answer.

    There is no setting that allows drag and drop reordering of NSTableView rows in Interface Builder. You need to implement certain NSTableViewDataSource methods, including:

    - tableView:acceptDrop:row:dropOperation:
    
    - (NSDragOperation)tableView:(NSTableView *)aTableView validateDrop:(id < NSDraggingInfo >)info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)operation
    
    - (BOOL)tableView:(NSTableView *)aTableView writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard *)pboard
    

    There are other SO question that address this reasonably thoroughly, including this one

    Apple link to Drag and Drop APIs.