可拖动标签 - ios [英] Draggable label - ios

查看:221
本文介绍了可拖动标签 - ios的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要求只在用户触摸并拖动时才移动标签。我无法确定用户是否触摸了该标签。我使用了touchesMoved方法(Swift 2)。下面是我的代码

I have a requirement to move a label around only when the user touches on it and drags. I cant find out whether the user touched that label or not. I have used the touchesMoved method(Swift 2). Below is my code

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    super.touchesBegan(touches as Set<UITouch>, withEvent: event) 
    let touch = touches.first

  if (touch!.view) == (moveLabel as UIView) // moveButton is my label
  {
    location = touch!.locationInView(self.view)
    moveLabel.center = location
  }
}

当我这样做时,我的标签不动:(
有人帮我请

When I do this, my label is not moving :( someone help me please

推荐答案

我一直在想你的问题,这是我的结果,你需要继承 UILabel 并且 init 你需要设置 userInteractionEnabled = true 然后重写此方法覆盖func touchesMoved( touches:设置< UITouch> ;,withEvent事件:UIEvent?)好吧,我的代码是这样的:

I had been thinking in your question, and this is my result, you need to subclass UILabel and in the init you need to set userInteractionEnabled = true and then override this method override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) well, my code is this:

Swift 3.1 Code

import UIKit

class draggableLabel: UILabel {


    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.layer.borderWidth = 1
        self.layer.borderColor = UIColor.red.cgColor
        self.isUserInteractionEnabled = true
    }



    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first;
        let location = touch?.location(in: self.superview);
        if(location != nil)
        {
        self.frame.origin = CGPoint(x: location!.x-self.frame.size.width/2, y: location!.y-self.frame.size.height/2);
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    }

}

Swift 2.2代码

import UIKit

class draggableLabel: UILabel {


    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.layer.borderWidth = 1
        self.layer.borderColor = UIColor.redColor().CGColor
        self.userInteractionEnabled = true
    }

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = touches.first;
        let location = touch?.locationInView(self.superview);
        if(location != nil)
        {
        self.frame.origin = CGPointMake(location!.x-self.frame.size.width/2, location!.y-self.frame.size.height/2);
        }
    }

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {

    }

}

希望这对你有所帮助,对我来说效果很好,这就是它的工作方式

Hope this helps you, for me works great, this is how it works

这篇关于可拖动标签 - ios的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆