I am currently using UIDragInteraction
and UIDropInteraction
made available in iOS 11 to make a simple drag and drop feature, where user could drag an UIImageView onto a UIView.
I realized that one unintuitive element to this is that the UIDragInteraction
requires a long press of at least a second to work. I was wondering if there is a way to shorten the long press duration? The docs on Apple doesn't seem to highlight this.
Thanks!
Implementation pasted below for reference:
class ViewController: UIViewController {
@IBOutlet var imageView: UIImageView!
@IBOutlet var dropArea: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let dragInteraction = UIDragInteraction(delegate: self)
imageView.addInteraction(dragInteraction)
dragInteraction.isEnabled = true
let dropInteraction = UIDropInteraction(delegate: self)
dropArea.addInteraction(dropInteraction)
}
}
extension ViewController: UIDragInteractionDelegate {
func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
guard let image = imageView.image
else { return [] }
let itemProvider = NSItemProvider(object: image)
return [UIDragItem(itemProvider: itemProvider)]
}
}
extension ViewController: UIDropInteractionDelegate {
func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
return UIDropProposal(operation: .copy)
}
func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
guard let itemProvider = session.items.first?.itemProvider,
itemProvider.canLoadObject(ofClass: UIImage.self)
else { return }
itemProvider.loadObject(ofClass: UIImage.self) { [weak self] loadedItem, error in
guard let image = loadedItem as? UIImage
else { return }
DispatchQueue.main.async {
self?.dropArea.image = image
}
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…