多个标签,我想通过触摸移动 我只是想让你在我创建的视图中移动
enter code here
@IBOutlet weak var cardView: UIView!
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
@IBOutlet weak var label3: UILabel!
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let position = touch.location(in: self.cardView)
print(position.x, position.y)
label.frame.origin = CGPoint(x:position.x-60,y:position.y-30)
}
}
答案 0 :(得分:1)
要在其超级视图中移动标签,您可以将UIPanGestureRecognizer添加到标签。 例如
func setGesture() -> UIPanGestureRecognizer {
var panGesture = UIPanGestureRecognizer()
panGesture = UIPanGestureRecognizer (target: self, action: #selector("handlePan:"))
panGesture.minimumNumberOfTouches = 1
panGesture.maximumNumberOfTouches = 1
return panGesture
}
//set the recognize in multiple views
lbl1.addGestureRecognizer(setGesture())
lbl2.addGestureRecognizer(setGesture())
答案 1 :(得分:0)
对于用手指移动物体,覆盖touchesMoved
方法就足够了。您在示例中遗漏的内容是,您应该从当前previousLocation
解除location
。以下是示例代码:
class MovableView: UIView {
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let oldLocation = touches.first?.previousLocation(in: self)
let newLocation = touches.first?.location(in: self)
move(with: CGPoint(x: (newLocation?.x)! - (oldLocation?.x)!, y: (newLocation?.y)! - (oldLocation?.y)!))
}
private func move(with offset: CGPoint) {
center = CGPoint(x: center.x + offset.x, y: center.y + offset.y)
}
}