可拖动的标签 – ios

只有当用户触摸并拖动标签时,我才需要移动标签。 我无法找出用户是否触摸过该标签。 我使用了touchesMoved方法(Swift 2)。 以下是我的代码

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 } } 

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

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

Swift 3.1代码

 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?) { } } 

希望这可以帮助你,对我来说工作很好,这是它的工作原理

在这里输入图像说明