我有包含两个标签的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 []
}
}发布于 2018-12-27 06:26:04
我尝试了您的代码并更改了您的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 []
}
}代码的最终结果:

https://stackoverflow.com/questions/53940017
复制相似问题