Categories: Swift Programming

Using UI Swipe and Pinch Gesture Recognizer with Swift

Hello everyone!
Today I’m going to show a simple way to use Swipe and Pinch gesture with Swift.

I have added the following images to my Assets folder on which I want to apply the Swipe and Pinch gesture.

Create a project and add a UIImageView to the controller.

From your Object Library drag and drop two UISwipeGestureRecognizer and set one swipe to Left and the other to Right.

Also add a UIPinchGestureRecognizer.

Create an action for UISwipeGestureRecognizer and connect both objects to the same action and in your controller.

 

//Array of image names
let images = ["pic7.png","pic9.png","pic15.png"]
var imageIndex = 0;
let maxIndex = 2;

and another for UIPinchGestureRecognizer.

 

Make UIImageView‘s reference outlet in the controller’s class.

 

In action of UISwipe

 

let leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("swipeImages:"));
let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("swipeImages:"));

leftSwipe.direction = .Left;
rightSwipe.direction = .Right;
view.addGestureRecognizer(leftSwipe)
view.addGestureRecognizer(rightSwipe)
if(sender.direction == .Left)
{
imageIndex++;
if(imageIndex > maxIndex)
{
imageIndex = 0;
}

}
if(sender.direction == .Right)
{
imageIndex--;

if(imageIndex < 0) { imageIndex = maxIndex; } } //Displaying Frames in UIImageView 
imageFrame.image = UIImage (named:images[imageIndex])

and in action of UIPinch

let lastScaleFactor:CGFloat = 1; let factor:CGFloat = sender.scale; if(factor > 1){
imageFrame.transform = CGAffineTransformMakeScale((lastScaleFactor + (factor - 1)), lastScaleFactor + (factor - 1));

}
else {
imageFrame.transform = CGAffineTransformMakeScale(lastScaleFactor * factor, lastScaleFactor * factor);

}

Connect UIImageView reference to UISwipe and UIPinch GestureRecognizer.

and Make sure that User Interaction is Enabled.

Finally run your app, you should be getting something like this.

Source on Github
So long. 🙂

Aaqib Hussain

Recent Posts

Things to know when moving to Germany

This article covers some important things you must know when you are considering a move…

3 years ago

Unit Testing in Android for Dummies

What is Unit Testing? In its simplest term, unit testing is testing a small piece…

4 years ago

Factory Design Pattern

In this article, you will learn about a type of Creational Design Pattern which is…

5 years ago

Creating Target specific Theme in iOS

In this tutorial, you will go through the use of targets to achieve two separate…

5 years ago

Facade Design Pattern

In this article, you will learn about a type of Structural Design Pattern which is…

5 years ago

Singleton Design Pattern

In this article you will learn about a type of Creational Design Pattern which is…

5 years ago