Custom view for Drag and Drop

元气小坏坏 提交于 2021-02-07 07:31:02

问题


I have set up my UITableView to use the new Drag and Drop APIs.

if #available(iOS 11, *) {
    self.tableView.dragDelegate = self
    self.tableView.dropDelegate = self
    self.tableView.dragInteractionEnabled = true
    navigationController?.navigationBar.prefersLargeTitles = false
}

Now, I implemented the method below to be able to use custom views for the d&d.

@available(iOS 11.0, *)
func dragInteraction(_ interaction: UIDragInteraction, previewForLifting item: UIDragItem, session: UIDragSession) -> UITargetedDragPreview? {
    print("Custom Preview method called!")
    let test = UITextView.init(frame: CGRect.init(x: 0, y: 0, width: 200, height: 200))
    test.text = "sfgshshsfhshshfshsfh"
    let dragView = interaction.view!
    let dragPoint = session.location(in: dragView)
    let target = UIDragPreviewTarget(container: dragView, center: dragPoint)
    return UITargetedDragPreview(view: test, parameters:UIDragPreviewParameters(), target:target)
}

However, this method never gets called. I never see the print() or my custom view. Any ideas as to what I'm doing wrong?


回答1:


You have to set previewProvider property when creating the UIDragItem.

let dragItem = UIDragItem(...)
dragItem.previewProvider = {
    print("Custom Preview method called!")
    let test = UITextView.init(frame: CGRect.init(x: 0, y: 0, width: 200, height: 200))
    test.text = "sfgshshsfhshshfshsfh"
    return UIDragPreview(view: test)
}

See: https://developer.apple.com/documentation/uikit/uidragitem/2890972-previewprovider?language=objc




回答2:


Are you using an iPhone? I am not certain it is currently working for customer UIViewController as of November 25, 2017 based on the following:

  • I downloaded the Apple sample project for drag-and-drop on an iPad
  • I added a breakpoint in dragInteraction and confirmed I could reach it
  • I modified the target to be a universal app (i.e. iPhone, too)
  • I ran on an iPhone 8 device and did not reach the breakpoint

As further suggestion, there is a property named dragInteractionEnabled for both UITableViewController and UICollectionViewController. For iPhone devices, the property is defaulted to false and, more importantly, the property is not even defined higher in UIViewController.



来源:https://stackoverflow.com/questions/45140854/custom-view-for-drag-and-drop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!