ios - 能够缩短 UIDragInteraction 的长按时间

标签 ios swift drag-and-drop uidragitem

我目前正在使用 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/

相关文章:

ios - 如何更改 UITabBarController 中的项目

ios - SceneKit——在 SCNNode 面对的方向上施加力

ios - 如何将实时表格 View 选择的单元格计数器作为 UIBarButtonItem

ios - 异步获取完成 : Is cell still being displayed?

ios - iPhone 重启后部署到 iphone 的 Xcode Swift 应用程序丢失 CoreData

c++ - 在拖放操作中交换 QTreeView 项目

ios - 调整大小以适合其 titleLabel 的 UIButton

ios - 使用 CGFloat 变量调用 func

Android:将ImageView拖离屏幕

javascript - 放下三个物体后触发图像变化