首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >未触发dragInteraction itemsForBeginning

未触发dragInteraction itemsForBeginning
EN

Stack Overflow用户
提问于 2018-12-27 05:09:20
回答 1查看 1K关注 0票数 0

我有包含两个标签的xib文件,我希望这些标签成为可拖动的。问题是itemsForBeginning函数从未启动过!我不知道我的代码中遗漏了什么!

代码语言:javascript
复制
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 []
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-27 06:26:04

我尝试了您的代码并更改了您的addDragInteraction方法

代码语言:javascript
复制
func addDragInteraction(){
    let interaction = UIDragInteraction(delegate: self)
    interaction.isEnabled = true
    self.addInteraction(interaction)
}

此外,你需要持有任何标签,然后再拖像长按压。

希望这是有帮助的

完整法典:

代码语言:javascript
复制
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 []
}
}

代码的最终结果:

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53940017

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档