【发布时间】:2018-01-30 19:08:58
【问题描述】:
我正在使用新的 Apple API 来启用自定义视图上的拖放交互。 问题是拖动源来自应用程序外部(Safari/照片/文件)。 有谁知道一种方法来检测拖动操作何时开始,这样我就可以放一个“放在这里”视图之类的东西 在我的自定义视图中?
谢谢
【问题讨论】:
标签: ios drag-and-drop ios11
我正在使用新的 Apple API 来启用自定义视图上的拖放交互。 问题是拖动源来自应用程序外部(Safari/照片/文件)。 有谁知道一种方法来检测拖动操作何时开始,这样我就可以放一个“放在这里”视图之类的东西 在我的自定义视图中?
谢谢
【问题讨论】:
标签: ios drag-and-drop ios11
首先,您需要将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()
}
委托方法,canHandleSession 的 UIDropInteractionDelegate 查询是否可以处理当前的删除会话:
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 方法。
【讨论】: