The Power of Pinching

Gan Chau
3 min readJul 14, 2015

--

A pinch gesture, or more specifically, a UIPinchGestureRecognizer, is one of several predefined gesture recognizers provided by the UIKit framework. Pinching is a continuous gesture because it takes place over a period of time and will keep sending messages to its target until the gesture ends. In contrast, a tap is a discrete gesture and will send one action message to its target.

image provide by Apple

As an example, I will demonstrate how to implement a pinch gesture using Xcode’s storyboard. The action triggered by the pinch gesture will either increase or decrease the view’s alpha property.

  1. To begin, we need to drag in a UIView from the object library into the View Controller in storyboard. Then create an outlet for the view so we can adjust its alpha property. Give it a background color so we can see its alpha change.
  2. Next, drag a UIPinchGestureRecognizer onto the View.

3. Create an action by Ctrl-dragging from the UIPinchGestureRecognizer to the view controller implementation file.

4. Implement the action method triggered by the pinch gesture. A scaleDifference property will save the scale value of the pinch gesture when the gesture ends. That way, whenever the user triggers the pinch gesture again in the future, it will continue where it left off. A local variable, brightness, will determine the view’s alpha value. This value will fall in between the range of 0.3 to 1.0.

- (IBAction)pinchGesturePinching:(UIPinchGestureRecognizer *)sender{// lowest brightness level is set at 0.3CGFloat brightness = MAX(0.3, sender.scale — self.scaleDifference);// restrict brightness from exceeding 1.0brightness = MIN(brightness, 1.0);// set alpha to brightness levelself.coloredView.alpha = brightness;NSLog(@”alpha:%f, scale:%f, difference:%f”, self.coloredView.alpha, sender.scale, self.scaleDifference);if (sender.state == UIGestureRecognizerStateEnded) 
{
// save the scale difference for next pinch gesture self.scaleDifference = 1.0 — self.coloredView.alpha; NSLog(@”Pinch ended”);}}

In summary, UIGestureRecognizers are powerful tools that make use of a device’s multitouch screen. This is only a small example of what they are capable of, but that is only because the complexity of the code is done for us behind the scene. The Apple documentation has more information of the various gestures that developers can implement into their own projects.

--

--