Dragging Views With Gestures

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.

Update: July 28, 2014. The rewritten version in Swift for iOS 8 and Xcode 6 is available here.

Open Xcode and create a new Single View Application. For product name, use DraggingViewsDemo and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices, and that the Use Storyboards checkbox is deselected and Use Automatic Reference Counting checkbox is selected.

First, let's create the views which we will place randomly on the screen. Add a new file to the project with the Objective-C class template.Name the class MyView with a Subclass of UIView. Go to myView.h and add a instance variable of type CGPoint.

@interface MyView: UIView 
CGPoint lastLocation;

This variable will keep track of the last position of a user's touch. Next, in MyView.m let's implement the initWithFrame method.

- (id)initWithFrame:(CGRect)frame
self = [super initWithFrame:frame];
if (self) {

UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(detectPan:)];
self.gestureRecognizers = @[panRecognizer];

// randomize view color
CGFloat hue = ( arc4random() % 256 / 256.0 ); // 0.0 to 1.0
CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from white
CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from black
UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];

self.backgroundColor = color;
return self;

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.

- (void) detectPan:(UIPanGestureRecognizer *) uiPanGestureRecognizer
CGPoint translation = [uiPanGestureRecognizer 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.

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
// Promote the touched view
[self.superview bringSubviewToFront:self];

// 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. In ViewController.h, import our view header file

#import "MyView.h"


In ViewController.m, implement the viewDidLoad method


[objc]- (void)viewDidLoad 
[super viewDidLoad];

self.view.backgroundColor = [UIColor blackColor];
CGFloat halfSizeOfView = 25.0f; NSInteger maxViews = 10;
CGSize insetSize = CGRectInset(self.view.bounds, 2*halfSizeOfView, 2*halfSizeOfView).size;

// Add the Views
for (int i = 0; i < maxViews; i++)
CGFloat pointX = random() % ((int)insetSize.width) + halfSizeOfView;
CGFloat pointY = random() % ((int)insetSize.height) + halfSizeOfView;
MyView *newView = [[MyView alloc] initWithFrame: CGRectMake(pointX, pointY, 50, 50)];
[self.view addSubview:newView];

There will be 10 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 DraggingViewsDemo at the ioscreator repository on github.