我目前在 iOS 11 中使用UIDragInteraction
并UIDropInteraction
提供了一个简单的拖放功能,用户可以将 UIImageView 拖到 UIView 上。
我意识到一个不直观的因素是UIDragInteraction
需要至少一秒钟的长按才能工作。我想知道是否有办法缩短长按时间?Apple上的文档似乎没有强调这一点。
谢谢!
实现粘贴在下面以供参考:
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
}
}
}
}