问题
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