Drag & Drop Reorder Rows on NSTableView

前端 未结 7 723
旧巷少年郎
旧巷少年郎 2020-12-08 11:21

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 thi

相关标签:
7条回答
  • 2020-12-08 12:01

    If your are moving only one row at the time you can use the following code:

        func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableViewDropOperation) -> Bool {
            let pasteboard = info.draggingPasteboard()
            guard let pasteboardData = pasteboard.data(forType: basicTableViewDragAndDropDataType) else { return false }
            guard let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: pasteboardData) as? IndexSet else { return false }
            guard let oldIndex = rowIndexes.first else { return false }
    
            let newIndex = oldIndex < row ? row - 1 : row
            tableView.moveRow(at: oldIndex, to: newIndex)
    
            // Dont' forget to update model
    
            return true
        }
    
    0 讨论(0)
提交回复
热议问题