ios - 未触发 dragInteraction itemsForBeginning
问题描述
我有包含两个标签的 xib 文件,我希望这些标签可以拖动。问题是 itemsForBeginning 函数从未触发!我不确定我的代码中缺少什么!
class EditSchduleLeftSide: UIView {
@IBOutlet weak var collaboration: UILabel!
@IBOutlet weak var deepwork: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.isUserInteractionEnabled = true
addDragInteraction()
}
func addDragInteraction(){
let interaction = UIDragInteraction(delegate: self)
self.addInteraction(interaction)
}
}
extension EditSchduleLeftSide: UIDragInteractionDelegate {
func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
let hitPoint = session.location(in: self)
if let hittedLabel = hitTest(hitPoint, with: nil) as? UILabel {
let provider = NSItemProvider(object: hittedLabel.text as! NSString)
let dragItem = UIDragItem(itemProvider: provider)
return [dragItem]
}
return []
}
}
解决方案
我试过你的代码,我改变了你的addDragInteraction
方法
func addDragInteraction(){
let interaction = UIDragInteraction(delegate: self)
interaction.isEnabled = true
self.addInteraction(interaction)
}
另外,您需要在拖动之前按住任何标签,例如长按。
希望这会有所帮助
完整代码:
class TmpView: UIView {
class func instanceFromNib() -> TmpView {
return UINib(nibName: "TmpView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! TmpView
}
@IBOutlet weak var collaboration: UILabel!
@IBOutlet weak var deepwork: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.isUserInteractionEnabled = true
collaboration.isUserInteractionEnabled = true
deepwork.isUserInteractionEnabled = true
self.layer.borderWidth = 2
addDragInteraction()
}
func addDragInteraction(){
let interaction = UIDragInteraction(delegate: self)
interaction.isEnabled = true
self.addInteraction(interaction)
}
}
extension TmpView: UIDragInteractionDelegate {
func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
let hitPoint = session.location(in: self)
if let hittedLabel = hitTest(hitPoint, with: nil) as? UILabel {
let provider = NSItemProvider(object: hittedLabel.text! as NSString)
let dragItem = UIDragItem(itemProvider: provider)
return [dragItem]
}
return []
}
}
您的代码的最终结果:
推荐阅读
- css - 子选择器和相邻兄弟选择器有什么区别?
- reactjs - 刷新 axios 拦截器中的令牌不起作用
- python - 如何从特定范围的单元格中获取值并将其复制到 Python 数据框中的特定范围?
- r - 插入符号包未在 Rstudio 中加载
- javascript - 如何在不编译 typescript 的情况下在 typescript monorepo 中使用 vs-code 和 ts-node 进行调试
- javascript - 如何使用按钮删除所有动态创建的元素
- terraform - Terraform - 无法将字符串变量传递给子模块
- json - Azure Durable Functions 我应该如何处理 TaskFailedExceptionDeserializationException
- javascript - Vue CLI 中导入的文件说明(App 与 App.vue 之间的区别)
- html - 如何设置复选框内容?