我目前正在使用iOS 11中提供的UIDragInteractionUIDropInteraction来创建简单的拖放功能,用户可以在其中将UIImageView拖到UIView上。

我意识到一个不直观的元素是UIDragInteraction需要长按至少一秒钟才能起作用。我想知道是否可以通过缩短长按时间? docs on 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
            }
        }
    }
}

最佳答案

没有明显的方法可以执行此操作,但是我正面临着同样的问题,并偷看了dragInteraction附加到的 View 的手势识别器。它是一个_UIDragLiftGestureRecognizer,它不是公共(public)API的一部分,但事实证明这只是UILongPressGestureRecognizer的子类。

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

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

关于ios - 能够缩短UIDragInteraction长按时间,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48175672/

10-13 01:42