Stuart Breckenridge

Implementing Drag and Drop with an NSManagedObject

Back in July I started adding the drag and drop API to The FFI List. At the time, I wrote:

What I want to do — and what I haven’t worked out yet — is dragging from the search table view on to the saved tab in order to save FFIs. It’ll take a bit more work, but I’m sure it’s doable.

It turns out this was easier than I thought: all I had to do was assign the NSManagedObject to the UIDragItem’s localObject variable (1), add a UIDropInteraction to the appropriate UITabBar subview (2), and make the UITabBarController conform to the UIDropInteractionDelegate protocol (3).

1 — Assign an NSManagedObject to the UIDragItem’s localObject variable:

let dragItem = UIDragItem(itemProvider: itemProvider)
dragItem.localObject = <#NSManagedObject#>

2 — Add a UIDropInteraction to the tab bar in viewDidLoad():

let dropInteraction = UIDropInteraction(delegate: self)
tabBar.subviews[1].addInteraction(dropInteraction)

3 — Make the UITabBarController conform to the UIDropInteractionDelegate protocol:

func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
    return session.hasItemsConforming(toTypeIdentifiers: [kUTTypePlainText as String])
}
    
func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
    return UIDropProposal(operation: UIDropOperation.move)
}
    
    
func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
    let ffi = session.items[0].localObject as! <#NSManagedObject#>
    // Necessary logic to parse the NSManagedObject
}

You can see it working over on YouTube.


— Supported by —