简体   繁体   中英

Drag and Dropping on a String/Images NSTableView Swift

Im trying to create a drag and drop system based on a table of cells (indexes from 1 to 17), which connects to a NSImage array, that gets modified according to the drag and drop result. My table seems to accept dragging (the number with a little bit of transparency is movable), but nothing happens when I drop. I suspect there is something wrong with my Type Registration, but I am kinda new at osx. Can someone help?

var images:[NSImage] = []

func getImages() {
    images = []
    for i in 50...66 {
        images.append(NSImage(named: "IMG_67\(i)")!)
    }
}

func tableViewSelectionDidChange(notification: NSNotification) {
    let table = notification.object
    let selection = table?.selectedRow
    imgView.image = images[selection!]
}

func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? {
    tableView.cell?.title = String(row)

    return row + 1
}

func numberOfRowsInTableView(tableView: NSTableView) -> Int {

    getImages()

    return images.count
}

func tableView(tableView: NSTableView, writeRowsWithIndexes rowIndexes: NSIndexSet, toPasteboard pboard: NSPasteboard) -> Bool {

    let data:NSData = NSKeyedArchiver.archivedDataWithRootObject(rowIndexes)
    let registeredTypes:[String] = [NSGeneralPboard] //Problem might be here
    pboard.declareTypes(registeredTypes, owner: self)
    pboard.setData(data, forType: NSGeneralPboard)

    return true
}

func tableView(tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableViewDropOperation) -> NSDragOperation {

    if dropOperation == .Above {
        return .Move
    }
    return .All
}

func tableView(tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableViewDropOperation) -> Bool {

    let data: NSData = info.draggingPasteboard().dataForType(NSGeneralPboard)!
    let rowIndexes: NSIndexSet = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! NSIndexSet
    let value: NSImage = images[rowIndexes.firstIndex]
    images.removeAtIndex(rowIndexes.firstIndex)
    if (row > images.count)
    {
        images.insert(value, atIndex: row - 1)
    } else {
        images.insert(value, atIndex: row)
    }
    tableView.reloadData()
    print("returning true") //Not getting called at all
    return true
}

After a deep search, I found that I had not registered my type! Newby mistake..

tableView.registerForDraggedTypes([NSGeneralPboard])

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM