首页 > 解决方案 > 未触发 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 []
    }
}

标签: iosswift

解决方案


我试过你的代码,我改变了你的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 []
}
}

您的代码的最终结果:

在此处输入图像描述


推荐阅读