MacOS Swift NSTableView with NSTokenFieldCell tracking which column drag started from

122 views Asked by At

I have a simple test program that has a 2 column NSTableView (View based), both columns have their cells set to NSTokenFieldCell. I also have a NSTokenField in this controller

I want to be able to drag and drop tokens from the table to the field. When I have 1 column this is working well. Now I have 2 columns I need to know which token to add to the field

Sample code:


class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate, NSTokenFieldDelegate {

    @IBOutlet weak var tableView: NSTableView!
    @IBOutlet weak var tokenField: NSTokenField!

let tokens = ["tok1","tok2","tok3","tok1","tok2","tok3","tok1","tok2","tok3","tok1","tok2","tok3","tok1","tok2","tok3","tok1","tok2","tok3"]
    let tokens2 = ["image","date","time","folder"]
    override func viewDidLoad() {
        super.viewDidLoad()

   }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

 func numberOfRows(in tableView: NSTableView) -> Int {
        return max(tokens.count,tokens2.count)
    }

    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        guard let vw = tableView.makeView(withIdentifier: tableColumn!.identifier, owner: self) as? NSTableCellView else {
            return nil
        }
        if tableColumn?.title == "Tokens" {
            vw.textField?.stringValue = tokens[row]
        }
        else
        {
            if row < tokens2.count {
                vw.textField?.stringValue = tokens2[row]
            }
            else {
            vw.textField?.stringValue = ""
            }
        }
        return vw
    }

// The bit where I need help 

func tableView(
        _ tableView: NSTableView,
        pasteboardWriterForRow row: Int)
        -> NSPasteboardWriting?
    {
            return tokens[row] as NSString //Here I need to return tokens2[row] if a token from column 2 was dragged and dropped
          
        }
    }

What I can't figure out is which column gets the click to initiate the drag and drop tableView.clickedColumn is always -1 None of the other functions such as this fire func tableView(_ tableView: NSTableView, updateDraggingItemsForDrag draggingInfo: NSDraggingInfo)

Update: I can get this function to fire as soon as I start the drag operation: func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forRowIndexes rowIndexes: IndexSet) Screen shot

I've tried to capture mouseDown but am not having any luck with it either. Any pointers?

1

There are 1 answers

0
Gazing South On

The NSTokenFieldCell didn't have its property set to selectable once set the NTTokenFieldCell and the NSTokenField worked as desired.