我要求只在用户触摸并拖动时才移动标签。我无法确定用户是否触摸过该标签。我使用了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
}
}
当我这样做时,我的标签没有移动:( 有人帮帮我
答案 0 :(得分:1)
我一直在思考你的问题,这是我的结果,你需要继承UILabel
并在init
中设置userInteractionEnabled = true
,然后覆盖此方法{{ 1}}好吧,我的代码是这样的:
Swift 3.1代码
override func touchesMoved(touches: Set<UITouch>, withEvent 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.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?) {
}
}
希望这对你有所帮助,对我来说效果很好,这就是它的工作原理