Reputation: 13
So I am creating an app with a grid that will create a node when I tap. Now, I am currently using PanGesture to drag and drop the node to a different location in the grid. Right now, I want the node I am dragging to be bigger (so it's easier for the user to see) and then go back to its size when it is dropped. So I used the "panGesture.state == begin" to implement a animation that will enlarge the node. However, this animation only begins when the node starts moving not when as soon as I touch it. According to the Apple API,
A pan gesture recognizer enters the began state as soon as the
**required amount of initial movement is achieved**
meaning my node won't be bigger until I start dragging my node.
Is there any way I can fix this?
Upvotes: 1
Views: 3433
Reputation: 2983
In pan gesture the .began means begin to move not begin to touch. You have to override func touchesBegan(_ touches: Set, with event: UIEvent?) function to get actual touch.
Upvotes: 1
Reputation: 310
You can use long press and pan gesture recognizers simultaneously. See code sample.
class ViewController: UIViewController, UIGestureRecognizerDelegate {
var dragView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.dragView = UIView(frame: CGRect(x: 100.0, y: 100, width: 50.0, height: 50.0))
self.dragView.backgroundColor = UIColor.red
let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(pan))
panRecognizer.delegate = self
self.dragView.addGestureRecognizer(panRecognizer)
let pressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(press))
pressRecognizer.minimumPressDuration = 0.0 // IMPORTANT
pressRecognizer.delegate = self
self.dragView.addGestureRecognizer(pressRecognizer)
self.view.addSubview(self.dragView)
}
@objc
func press(gestureRecognizer: UILongPressGestureRecognizer) {
switch gestureRecognizer.state {
case .began:
UIView.animate(withDuration: 0.1, animations: {
self.dragView.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
})
case .cancelled, .ended, .failed:
UIView.animate(withDuration: 0.1, animations: {
self.dragView.transform = CGAffineTransform.identity
})
default: break
}
}
@objc
func pan(gestureRecognizer: UIPanGestureRecognizer) {
switch gestureRecognizer.state {
case .changed:
var center = self.dragView.center
let translation = gestureRecognizer.translation(in: self.dragView)
center.x += translation.x
center.y += translation.y
self.dragView.center = center
gestureRecognizer.setTranslation(CGPoint.zero, in: self.dragView)
default: break
}
}
// MARK: UIGestureRecognizerDelegate
@objc
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true // IMPORTANT
}
}
Upvotes: 1