能够缩短UIDragInteraction的长按时间

das*_*ist 4 drag-and-drop ios swift uidragitem

我当前正在使用iOS 11 UIDragInteractionUIDropInteraction使其可用,以提供简单的拖放功能,用户可以在其中将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
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 6

没有明显的方法可以执行此操作,但是我正面临着同样的问题,并且对附有dragInteraction的视图的手势识别器进行了窥视。它_UIDragLiftGestureRecognizer不是公共API的一部分,但事实证明这只是的子类UILongPressGestureRecognizer

因此,在将您UIDragInteraction的视图添加到视图中后,将该视图添加到视图层次结构中(由于我使用的是自定义UIView子类,因此我刚刚将其添加到了didMoveToSuperview()),您可以执行以下操作:

if let longPressRecognizer = gestureRecognizers?.compactMap({ $0 as? UILongPressGestureRecognizer}).first {
    longPressRecognizer.minimumPressDuration = 0.1 // your custom value
}
Run Code Online (Sandbox Code Playgroud)