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 Code
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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…