Reputation:
Multiple labels, I want to move by touch I just want you to move in the view I created
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)
}
}
Upvotes: 0
Views: 1151
Reputation: 2252
for moving labels within its superview you can add UIPanGestureRecognizer to label. For Example
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())
Upvotes: 1
Reputation: 320
For moving objects with a finger, it is enough to override touchesMoved
method. The thing you have missed in your example is that you should distruct previousLocation
from current location
. Here is a sample code:
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)
}
}
Upvotes: 0