【问题标题】:How to detect drag events from outside the app in iOS 11?如何在 iOS 11 中检测来自应用程序外部的拖动事件?
【发布时间】:2018-01-30 19:08:58
【问题描述】:

我正在使用新的 Apple API 来启用自定义视图上的拖放交互。 问题是拖动源来自应用程序外部(Safari/照片/文件)。 有谁知道一种方法来检测拖动操作何时开始,这样我就可以放一个“放在这里”视图之类的东西 在我的自定义视图中?

谢谢

【问题讨论】:

    标签: ios drag-and-drop ios11


    【解决方案1】:

    首先,您需要将UIDropInteraction 添加到您尝试在其上放置内容的任何视图中。

    override func viewDidLoad() {            
        let dropInteraction = UIDropInteraction.init(delegate: self)
    
        //The target view could be anything, a UILabel, UIImageView, UIView as long as it is a descendant of UIView
        dropTargetView.isUserInteractionEnabled = true //Very important
        dropTargetView.addInteraction(dropInteraction)
    
        super.viewDidLoad()
    }
    

    委托方法,canHandleSessionUIDropInteractionDelegate 查询是否可以处理当前的删除会话:

    extension ViewController: UIDropInteractionDelegate {
        func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
            return session.hasItemsConforming(toTypeIdentifiers: ["kUTTypeImage"]) && session.items.count == 1
        }
    }
    

    如果方法返回 true,您几乎可以在这种情况下显示“将物品放在此处”的图像。

    您无法检查用户拖动的实际数据,因为当交互调用此方法时它不可用。此方法中只有数据类型可用 (canHandleSession)。

    如果您想在用户拖动拖放区域内的内容的过程中进行控制,则应使用sessionDidUpdate 委托方法。 在这里,您将能够了解应用外部的拖动事件(回答您的问题)。

    func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
            
            let dropLocation = session.location(in: self.view)
            let dropOperation: UIDropOperation
            
            //Here you will know if the drag that user performs is inside your expected area, so you can show your "Drop here" graphic here.
            if self.view.frame.contains(dropLocation) {
                //If you happen to drag and drop from a different app, localDragSession will be nil
                dropOperation = session.localDragSession == nil ? .copy : .cancel 
            } else {
                dropOperation = .cancel
            }
            
            return UIDropProposal.init(operation: dropOperation)
        }
    

    最后要执行 drop,实现 performDrop 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-19
      • 2018-02-14
      • 2021-01-31
      • 2012-05-02
      • 2010-12-17
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      相关资源
      最近更新 更多