Skip to content

Instantly share code, notes, and snippets.

@ivan3bx
Last active August 29, 2015 14:22
Show Gist options
  • Save ivan3bx/46b26f25b86ac706e361 to your computer and use it in GitHub Desktop.
Save ivan3bx/46b26f25b86ac706e361 to your computer and use it in GitHub Desktop.
Q&D example of UIPanGestureRecognizer in Swift, dragging a square around
class ViewController: UIViewController {
@IBOutlet weak var square: UIView!
var squareMidpoint:CGPoint = CGPointZero
@IBAction func handlePan(recognizer: UIPanGestureRecognizer) {
let hitInRect = CGRectContainsPoint(square.frame, recognizer.locationInView(self.view))
let isMoving = (squareMidpoint != CGPointZero)
switch(recognizer.state) {
case .Began where hitInRect:
squareMidpoint = square.center
case .Changed where isMoving:
let translation = recognizer.translationInView(self.view)
let newX = squareMidpoint.x + translation.x
let newY = squareMidpoint.y + translation.y
square.center = CGPoint(x: newX, y: newY)
default:
squareMidpoint = CGPointZero
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment