Dragging Views with Gestures Tutorial in iOS8 with Swift

The strength of iOS lies in the interaction using touches and gestures. In this tutorial we'll display some custom views, which we can drag using the pan gesture recognizer. This tutorial is written in Swift so you will need Xcode 6. It can be downloaded at Apple's developer portal.

Open Xcode and create a new Single View Application. For product name, use iOS8SwiftDraggingViewsTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to the Storyboard and change the width to compact. This will change the view to a iPhone portrait mode. 

First, let's create the views which we will place randomly on the screen. Add a new class file to the project with File->New -> File -> iOS -> Source -> Cocoa Touch Class. Name the class MyView with a Subclass of UIView.

Go to myView.swift and add a variable of type CGPoint.

var lastLocation:CGPoint = CGPointMake(0, 0)

This variable will keep track of the last position of a user's touch. Next, implement the init method.

override init(frame: CGRect) {
  super.init(frame: frame)
  // Initialization code
  var panRecognizer = UIPanGestureRecognizer(target:self, action:"detectPan:")
  self.gestureRecognizers = [panRecognizer]
  //randomize view color
  let blueValue = CGFloat(Int(arc4random() % 255)) / 255.0
  let greenValue = CGFloat(Int(arc4random() % 255)) / 255.0
  let redValue = CGFloat(Int(arc4random() % 255)) / 255.0
  self.backgroundColor = UIColor(red:redValue, green: greenValue, blue: blueValue, alpha: 1.0)

First we attach a pan gesture recognizer to the view. Using this recognizer we can click and drag a view to a new position. Next, we create a random color, which we assign to the background color property of our view. implement the detectPan method, which will be called when a pan gesture is recognized.

func detectPan(recognizer:UIPanGestureRecognizer) {
  var translation  = recognizer.translationInView(self.superview!)
  self.center = CGPointMake(lastLocation.x + translation.x, lastLocation.y + translation.y)

The translation variable detects the new coordinates of the view when panning. The center of the view will be adjusted according to the changed coordinates. When the user clicks on a view the touchesBegan:withEvent method is called. Let's implement this method.

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
  // Promote the touched view
  // Remember original location
  lastLocation = self.center

When the view is clicked, the current view will be displayed in front of the other views and the center of the view will be assigned to the lastlocation variable. Now, our custom view is ready, let's move over to our view controller. Implement the viewDidLoad function in ViewController.swift

override func viewDidLoad() {
  // Do any additional setup after loading the view, typically from a nib.
  let halfSizeOfView = 25.0
  let maxViews = 25
  let insetSize = CGRectInset(self.view.bounds, CGFloat(Int(2 * halfSizeOfView)), CGFloat(Int(2 * halfSizeOfView))).size
  // Add the Views
  for i in 0..<maxViews {
    var pointX = CGFloat(UInt(arc4random() %  
    var pointY = CGFloat(UInt(arc4random() % 
    var newView = MyView(frame: CGRectMake(pointX, pointY, 50, 50))      

There will be 25 custom views of size 50 by 50 and added to the main view. The custom view will be placed randomly on the main view. Build and Run the project. Click and drag a view and you will see the views will always be in front of the other views.

You can download the source code of the iOS8SwiftDraggingViewsTutorial at the ioscreator repository on github.