UIPanGestureRecognizer to make draggable UIView in iOS Swift

 

This tutorial has been updated for X code 7.3 & swift 2.2

Many new apps are replacing buttons & labels with gestures. It helps you reduce clutter from your screen without loosing functionality. So today we are going to learn basics of uipangesturerecognizer. And how to create gesture recognizer dependancies in case you have multiple gesture recognizer set to one view.

  1. First lets set up the x code project as usual. Create new single view application X code project. Set project name to pan gesture demo and save it on your desktop.

new x code project

 

2. Go to main storyboard and select view controller. Set its size iPhone 4-inch in attribute section.

size iPhone 4 inch

 

3. Drag UIView to view controller & set its dimension as follows

set view dimenstions

 

4. Set its color to yellow

set view color to yellow

 

5. Add pan gesture to this yellow view & verify that its connected to correct view.

add pan gesture to yellow view

6. Connect pan gesture to swift file

pan gesture to swift file

 

7. Add following code in pan gesture action

@IBAction func panYellowView(sender: UIPanGestureRecognizer) {

    let translation = sender.translationInView(self.view)

    sender.view!.center = CGPoint(x: sender.view!.center.x + translation.x, y: sender.view!.center.y + translation.y)

    sender.setTranslation(CGPointZero, inView: self.view)

}

Instead of hard coding yellow view we are using sender. This way you can use exact same code for different view or connect same method to another view. Also because we are using sender; make sure you have connected pan gesture to yellow view.

Now build and run app in iPhone 5s & drag the yellow view

pan yellow view
Download X code file
Challenge 1: Change yellow views color from yellow to green on tap

When you have pan & tap gesture active on same view you will notice that if you drag yellow view just a little then it changes color to green. Your next challenge is to not change yellow view color whenever pan is active.

Challenge 2: Create gesture dependency so when pan is active yellow view will not change color.

tap & pan yellow view
Download Challenge Solution

Total 12 Votes
1

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?