The UIKit framework provides predefined gesture recognizers that detect common gestures. Gesture recognizers are objects that you attach to a view, which allows the view to respond to actions. In this tutorial we will display an image, which can be scaled up and down with the pinch gesture.
Open Xcode and create a new Single View Application. For product name, use ImagePinchDemo 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 our User Interface. Go to ViewController.xib. Drag a Image View to the main View, resize and center the Image View. The main View should look like this.
Next, add and drag a Pinch Gesture Recognizer to the Image View, which means that the gesture is applied only to our image and not the whole view. Select the Assistant Editor button and open the ViewController.m file. Ctrl and drag from the imageView to the @interface section to create an outlet.
Next, Ctrl and drag from the Pinch Gesture Recognizer to the @interface section to create an IBAction method.
As you can see the following code is generated in the @interface section
@interface ViewController ()
@property (nonatomic, weak) IBOutlet UIImageView *image;
- (IBAction)scaleImage:(UIPinchGestureRecognizer *)recognizer;
Change the viewDidLoad in ViewController.m
self.view.backgroundColor = [UIColor whiteColor];
UIImage *image = [UIImage imageNamed:@"xcode.jpeg"];
self.myImageView.image = image;
The xcode.jpeg image is loaded and inserted into the Image View.
Next, implement the scaleImage IBAction method
- (IBAction)scaleImage:(UIPinchGestureRecognizer *)recognizer
recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);
recognizer.scale = 1;
Every view has a transform that is applied to it, which you can think of as information scale that should be applied to the view. We update the view’s transform based on the gesture.
Since we’re updating the view each time the gesture updates, we reset the scale back to the default state.
Build and Run, and pinch to scale the image.
You can download the source code of the ImagePinchDemo at the ioscreator repository on github.