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.
1 2 3 4 |
//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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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
1 2 3 4 5 6 7 8 |
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.
[vimeo 151238307]
Source on Github
So long. 🙂