IOS gesture Operations (drag, knead, rotate, click, long Press, light Sweep, custom) _ios

Source: Internet
Author: User
Tags touch uikit

The following is an illustrated way to share the following iOS gesture operations (drag, knead, rotate, click, long Press, light Sweep, custom) related content.

1, Uigesturerecognizer Introduction
Gesture recognition is very important in IOS, and he greatly improves the ease of use of mobile devices.

IOS system after 3.2, he provides a number of common gestures (uigesturerecognizer), developers can directly use them for gesture operation.

Uipangesturerecognizer (drag)

Uipinchgesturerecognizer (kneading)

Uirotationgesturerecognizer (rotation)

UITapGestureRecognizer (click)

Uilongpressgesturerecognizer (Long Press)

Uiswipegesturerecognizer (Light sweep)

In addition, you can implement custom gestures (gesture recognizer classes) by inheriting the Uigesturerecognizer class.

PS: When you customize gestures, you need to #import <uikit/uigesturerecognizersubclass.h>, generally the following methods should be implemented:

Copy Code code as follows:

-(void) reset;

-(void) Touchesbegan: (Nsset *) touches withevent: (Uievent *) event;
-(void) touchesmoved: (Nsset *) touches withevent: (Uievent *) event;
-(void) touchesended: (Nsset *) touches withevent: (Uievent *) event;
-(void) touchescancelled: (Nsset *) touches withevent: (Uievent *) event;
The above methods are declared in the category Uigesturerecognizer (uigesturerecognizerprotected), and more method declarations are available on your own

The inheritance relationship of the Uigesturerecognizer is as follows:

2. Gesture Status
In six gesture recognition, only one gesture is discrete gesture, he is uitapgesturerecognizer.

Discrete gestures are characterized by the fact that once the recognition cannot be canceled, a gesture action event (the callback method specified when the gesture is initialized) is invoked only once.

In other words, the other five gestures are sequential gestures, and the continuous gesture is characterized by multiple calls to gesture manipulation events, and the gesture can be canceled after continuous gesture recognition. You can see from the figure below that the number of call action events is different:

The gesture status is enumerated as follows:

Copy Code code as follows:

typedef ns_enum (Nsinteger, uigesturerecognizerstate) {
Uigesturerecognizerstatepossible,//has not yet recognized what gesture operation (but may have triggered a touch event), default state
Uigesturerecognizerstatebegan,//gesture has started, has been recognized at this time, but this process may be changed, gesture operation has not been completed
Uigesturerecognizerstatechanged,//gesture status change
uigesturerecognizerstateended,//Gesture recognition operation completed (at this point the finger has been released)
Uigesturerecognizerstatecancelled,//gesture canceled, revert to default state
Uigesturerecognizerstatefailed,//gesture recognition failed, revert to default state
Uigesturerecognizerstaterecognized = uigesturerecognizerstateended/gesture recognition complete, with uigesturerecognizerstateended
};

For discrete gesture Uitapgesturerecgnizer is either recognized or failed, click (False point set by the number of times to 1, and do not add a long press gesture) go down one time not to release then nothing will happen, loosen the finger immediately recognize and invoke the action event, and the status is 3 (completed).
But continuous gestures are a bit more complicated, in the case of rotating gestures, if two hands are pointing down without doing anything, the gesture is not recognized (because we have not yet rotated) but it has actually triggered the touch start event, is in state 0, and if the rotation is recognized at this point, the corresponding action event is invoked. At the same time the state becomes 1 (gesture begins), but state 1 is only for a moment, then the state becomes 2 (because our rotation needs to last for a while), and the action event is repeated (if printing in the event repeats 2), releasing the finger, the state becomes 3, and 1 action events are invoked.

3. Steps to use gestures
Using gestures is simple and is divided into three steps:

Creates an instance of the gesture Recognizer object. When created, specifies a callback method that executes the callback method when the gesture begins, changes, or ends.

Sets the associated properties of the gesture Recognizer object instance (optional)

Add to the View you want to identify. Each gesture corresponds to only one view, and when the screen touches within the bounds of the view, the callback method is executed if the gesture is the same as the reservation.

PS: A gesture can only correspond to one view, but a view can have multiple gestures. It is recommended that these gestures be tested on the real machine and that the simulator is not easy to operate and may result in a failure of the gesture. (When the simulator tests kneading and rotating gestures, hold down the option key, then use the touchpad or mouse to operate)

4, the example explains
Function Description:

Attach to two picture views Uiimageview have "drag", "kneading", "Rotation", "click";

The "Light Sweep" and "custom gesture Kmgesturerecognizer" are appended to the root view UIView.

Dragging: Moving the current picture view position

Kneading: Zooming in the current picture view

Rotate: Rotate the current picture view angle

Click: Double-click to restore zoom, angle rotation, opacity of the current picture view

Long press: Sets the opacity of the current picture view to 0.7

Light sweep: Left and right light sweep set two picture view centered and positioned at a specific offset perpendicular to the center

Custom gestures: Tickle function, left and right sweep 3 times or more, set two picture view is centered, at the same time with a specific offset horizontally centered

The effect is as follows:

KMGestureRecognizer.h #import <UIKit/UIKit.h> typedef ns_enum (Nsuinteger, Direction) {directionunknown, D
 
 Irectionleft, directionright}; @interface Kmgesturerecognizer:uigesturerecognizer @property (Assign, nonatomic) Nsuinteger Ticklecount; Scratch the number of times @property (assign, nonatomic) Cgpoint Currentticklestart; The current tickling start coordinates the position @property (assign, nonatomic) Direction lastdirection; The final Tickle direction @end kmgesturerecognizer.m #import "KMGestureRecognizer.h" #import <uikit/uigesturerecognizersubclass. 
  h> @implementation kmgesturerecognizer #define kminticklespacing 20.0 #define KMAXTICKLECOUNT 3-(void) Reset {
  _ticklecount = 0;
  _currentticklestart = Cgpointzero;
  
  _lastdirection = Directionunknown;
  if (self.state = = uigesturerecognizerstatepossible) {self.state = uigesturerecognizerstatefailed;
  }-(void) Touchesbegan: (Nsset *) touches withevent: (Uievent *) Event {Uitouch *touch = [touches anyobject]; _currentticklestart = [Touch locAtionInView:self.view]; Set the current tickle start coordinate position}-(void) touchesmoved: (Nsset *) touches withevent: (Uievent *) event {//"current tickle start coordinate position" and "move after coordinate position" for X-axis value ratio
  The Uitouch *touch = [touches anyobject] is obtained by moving left or right;
  Cgpoint tickleend = [Touch LocationInView:self.view];
  CGFloat ticklespacing = tickleend.x-_currentticklestart.x; Direction currentdirection = ticklespacing < 0?
  
  Directionleft:directionright; Whether the X-axis spacing value of the move meets the requirements, enough large if (ABS (ticklespacing) >= kminticklespacing) {//To determine if there are three different directions of action, and if so, the callback method is executed if (_la
    Stdirection = = Directionunknown | |
    (_lastdirection = = Directionleft && currentdirection = = directionright) | | (_lastdirection = = Directionright && currentdirection = = directionleft))
    {_ticklecount++;
    _currentticklestart = Tickleend;
    
    _lastdirection = currentdirection; if (_ticklecount >= kmaxticklecount && self.state = = uigesturerecognizerstatepossible) {self.state = UIGe
     sturerecognizerstateended;NSLog (@ "Custom gesture succeeds, will execute callback method");
 }}-(void) touchesended: (Nsset *) touches withevent: (Uievent *) event {[Self reset];
 }-(void) touchescancelled: (Nsset *) touches withevent: (Uievent *) event {[Self reset]; @end ViewController.h #import <UIKit/UIKit.h> #import "KMGestureRecognizer.h" @interface viewcontroller:uiv
Iewcontroller @property (Strong, nonatomic) Uiimageview *IMGV;
@property (Strong, nonatomic) Uiimageview *imgv2;

@property (Strong, nonatomic) Kmgesturerecognizer *customgesturerecognizer; @end viewcontroller.m #import "ViewController.h" @interface Viewcontroller ()-(void) Handlepan: (Uipangesturerecogni
 Zer *) recognizer;
 -(void) Handlepinch: (Uipinchgesturerecognizer *) recognizer;
 -(void) Handlerotation: (Uirotationgesturerecognizer *) recognizer;
 -(void) Handletap: (UITapGestureRecognizer *) recognizer;
 -(void) Handlelongpress: (Uilongpressgesturerecognizer *) recognizer;
 -(void) Handleswipe: (Uiswipegesturerecognizer *) recognizer; -(VOID) Handlecustomgesturerecognizer: (Kmgesturerecognizer *) recognizer;
 -(void) Bindpan: (Uiimageview *) Imgvcustom;
 -(void) Bindpinch: (Uiimageview *) Imgvcustom;
 -(void) Bindrotation: (Uiimageview *) Imgvcustom;
 -(void) Bindtap: (Uiimageview *) Imgvcustom;
 -(void) Bindlongpress: (Uiimageview *) Imgvcustom;
 -(void) bindswipe;
 -(void) Bingcustomgesturerecognizer;
 -(void) Layoutui;
  
  @end @implementation Viewcontroller-(void) viewdidload {[Super viewdidload];
 [Self layoutui];
  }-(void) didreceivememorywarning {[Super didreceivememorywarning];
 Dispose of any of the can is recreated. #pragma mark-Handle gesture Operation/** * Handle drag gesture * * @param recognizer Drag gesture Recognizer Object instance/-(void) Handlepan: (Uipangesturerecogniz
  
  ER *) Recognizer {//view predecessor operation [Recognizer.view.superview BringSubviewToFront:recognizer.view];
  Cgpoint Center = recognizer.view.center;
  CGFloat Cornerradius = RECOGNIZER.VIEW.FRAME.SIZE.WIDTH/2; Cgpoint translation = [recognizer Translationinview:Self.view];
  NSLog (@ "%@", Nsstringfromcgpoint (translation));
  Recognizer.view.center = Cgpointmake (center.x + translation.x, center.y + translation.y);
  
  [Recognizer Settranslation:cgpointzero InView:self.view]; if (recognizer.state = = uigesturerecognizerstateended) {//The length of the speed vector is computed, the glide will be short when he is less than 200 cgpoint velocity = [Recognizer vel
  OcityInView:self.view];
  CGFloat magnitude = sqrtf ((velocity.x * velocity.x) + (VELOCITY.Y * velocity.y));
  CGFloat slidemult = magnitude/200; NSLog (@ "magnitude:%f, Slidemult:%f", magnitude, slidemult);
  e.g. 397.973175, slidemult:1.989866//calculation of an endpoint float Slidefactor = 0.1 * Slidemult based on speed and velocity factors;
  Cgpoint finalpoint = Cgpointmake (center.x + (velocity.x * slidefactor), CENTER.Y + (VELOCITY.Y * slideFactor)); Limit the minimum [Cornerradius] and maximum boundary values [Self.view.bounds.size.width-cornerradius] to avoid dragging out screen boundaries Finalpoint.x = MIN (
  Finalpoint.x, Cornerradius), Self.view.bounds.size.width-cornerradius); Finalpoint.y = MIN (finalPoint.y, Cornerradius), Self.view.bounds.size.height-cornerradius); Use UIView animation to glide view to the finish line [UIView animatewithduration:slidefactor*2 delay:0 options:uiviewanimationoption
      Curveeaseout animations:^{recognizer.view.center = finalpoint;
 } Completion:nil]; }/** * Processing kneading gesture * * @param recognizer kneading gesture Recognizer Object instance * * (void) Handlepinch: (Uipinchgesturerecognizer *) recognizer {Cgflo
 at scale = Recognizer.scale; Recognizer.view.transform = Cgaffinetransformscale (recognizer.view.transform, scale, scale);
The cumulative change is carried out on the basis of reduced magnification, which is different from: The Cgaffinetransformmakescale method is used to change the Recognizer.scale = 1.0 under the original size; /** * Processing rotary gesture * * @param recognizer Rotation gesture Recognizer Object instance/-(void) Handlerotation: (Uirotationgesturerecognizer *) recognizer {R
 Ecognizer.view.transform = Cgaffinetransformrotate (Recognizer.view.transform, recognizer.rotation);
 recognizer.rotation = 0.0; /** * Processing Point Press gesture * * @param recognizer Point by Gesture Recognizer Object instance/-(void) Handletap: (UitapgesturerecogniZer *) Recognizer {UIView *view = Recognizer.view;
  View.transform = Cgaffinetransformmakescale (1.0, 1.0);
  View.transform = cgaffinetransformmakerotation (0.0);
 View.alpha = 1.0; /** * Processing Long press gesture * * @param recognizer Point by Gesture Recognizer Object instance * * (void) Handlelongpress: (Uilongpressgesturerecognizer *) Recogn
 Izer {//long press, set opacity to 0.7 recognizer.view.alpha = 0.7;
  /** * Processing Light sweep gesture * * @param recognizer Light sweep gesture Recognizer Object instance/-(void) Handleswipe: (Uiswipegesturerecognizer *) Recognizer {
   Code block way encapsulates the operation method void (^positionoperation) = ^ () {Cgpoint newpoint = Recognizer.view.center;
   Newpoint.y-= 20.0;
   
   _imgv.center = Newpoint;
   Newpoint.y + 40.0;
  _imgv2.center = Newpoint;
  
  }; Depending on the direction of the light sweep, different control switch (recognizer.direction) {case uiswipegesturerecognizerdirectionright: {positionoperation (
    );
   Break
    Case Uiswipegesturerecognizerdirectionleft: {positionoperation ();
   Break
   Case Uiswipegesturerecognizerdirectionup: {break;
}   Case Uiswipegesturerecognizerdirectiondown: {break; /** * Handles Custom gesture * * @param recognizer Custom Gesture Recognizer Object instance/-(void) Handlecustomgesturerecognizer: (KMGESTURERECOG
   Nizer *) recognizer {//code block mode encapsulation operation method Void (^positionoperation) = ^ () {Cgpoint newpoint = Recognizer.view.center;
   Newpoint.x-= 20.0;
   
   _imgv.center = Newpoint;
   Newpoint.x + 40.0;
  _imgv2.center = Newpoint;
  
  };
 Positionoperation (); #pragma mark-bind gesture Operation/** * bind drag gesture * * @param imgvcustom bound to Picture View object instance * *-(void) Bindpan: (Uiimageview *) IMGVCU Stom {Uipangesturerecognizer *recognizer = [[Uipangesturerecognizer alloc] Initwithtarget:self Act
  Ion: @selector (Handlepan:)];
 [Imgvcustom Addgesturerecognizer:recognizer]; /** * Binding kneading gesture * * @param imgvcustom bound to Picture View object instance/-(void) Bindpinch: (Uiimageview *) Imgvcustom {uipinchgesture Recognizer *recognizer = [[Uipinchgesturerecognizer alloc] initwithtarget:self action: @selEctor (handlepinch:)];
  [Imgvcustom Addgesturerecognizer:recognizer];
 [Recognizer RequireGestureRecognizerToFail:imgVCustom.gestureRecognizers.firstObject]; /** * Binding Rotation gesture * * @param imgvcustom bound to the Picture View object instance/-(void) Bindrotation: (Uiimageview *) Imgvcustom {Uirotationg Esturerecognizer *recognizer = [[Uirotationgesturerecognizer alloc] initwithtarget:self action: @sel
  Ector (handlerotation:)];
 [Imgvcustom Addgesturerecognizer:recognizer]; /** * Bind point by gesture * * @param imgvcustom bound to Picture View object instance/-(void) Bindtap: (Uiimageview *) Imgvcustom {Uitapgesturereco Gnizer *recognizer = [[UITapGestureRecognizer alloc] initwithtarget:self action: @selector (Handletap:)
  ];
  Use a finger to double-click, only trigger the point by gesture recognizer recognizer.numberoftapsrequired = 2;
  recognizer.numberoftouchesrequired = 1;
 [Imgvcustom Addgesturerecognizer:recognizer]; /** * Binding Length by gesture * * @param imgvcustom bound to Picture View object instance/-(void) Bindlongpress: (Uiimageview *) Imgvcustom {UilongPressgesturerecognizer *recognizer = [[Uilongpressgesturerecognizer alloc] initwithtarget:self action: @selector (
  Handlelongpress:)]; Recognizer.minimumpressduration = 0.5;
 Set minimum length by time; default is 0.5 seconds [imgvcustom Addgesturerecognizer:recognizer];  /** * Bind the light sweep gesture, support the four-direction light sweep, but different directions to define the light sweep gesture * *-(void) Bindswipe {//Right light sweep gesture Uiswipegesturerecognizer *recognizer =
  [[Uiswipegesturerecognizer alloc] initwithtarget:self action: @selector (handleswipe:)]; Recognizer.direction = Uiswipegesturerecognizerdirectionright;
  Set the light sweep direction, the default is Uiswipegesturerecognizerdirectionright, that is, the right light sweep [Self.view Addgesturerecognizer:recognizer]; [Recognizer Requiregesturerecognizertofail:_customgesturerecognizer]; Set to custom Tickle gesture priority recognition//left light gesture recognizer = [[Uiswipegesturerecognizer alloc] initwithtarget:self action:
  @selector (handleswipe:)];
  Recognizer.direction = Uiswipegesturerecognizerdirectionleft;
  [Self.view Addgesturerecognizer:recognizer]; [Recognizer RequiregestuRerecognizertofail:_customgesturerecognizer]; Set to custom Tickle gesture priority Recognition}/** * Binding custom tickle gesture; Determine if there are three different directions of the action, if there is a gesture to end, will execute the callback method * *-(void) Bingcustomgesturerecognizer {//when r When Ecognizer.state is uigesturerecognizerstateended, the callback method is executed Handlecustomgesturerecognizer://_customgesturerecognizer
  = [Kmgesturerecognizer new]; _customgesturerecognizer = [[Kmgesturerecognizer alloc] initwithtarget:self action: @selector (Handlecusto
  Mgesturerecognizer:)];
 [Self.view Addgesturerecognizer:_customgesturerecognizer];
  }-(void) Layoutui {//Picture view _IMGV uiimage *img = [uiimage imagenamed:@ "Emoticon_tusiji_icon"];
  CGFloat Cornerradius = img.size.width;
  _IMGV = [[Uiimageview alloc] initwithimage:img];
  _imgv.frame = CGRectMake (20.0, 20.0, Cornerradius * 2, Cornerradius * 2);
  _imgv.userinteractionenabled = YES;
  _imgv.layer.maskstobounds = YES;
  _imgv.layer.cornerradius = Cornerradius;
  _imgv.layer.borderwidth = 2.0; _imgv.layer.bordercolor = [Uicolor graycolor].
  Cgcolor;
  
  [Self.view ADDSUBVIEW:_IMGV];
  Picture View _imgv2 img = [uiimage imagenamed:@ "Emoticon_tusiji_icon2"];
  Cornerradius = Img.size.width;
  _imgv2 = [[Uiimageview alloc] initwithimage:img];
  _imgv2.frame = CGRectMake (20.0, 40.0 + _imgv.frame.size.height, Cornerradius * 2, Cornerradius * 2);
  _imgv2.userinteractionenabled = YES;
  _imgv2.layer.maskstobounds = YES;
  _imgv2.layer.cornerradius = Cornerradius;
  _imgv2.layer.borderwidth = 2.0; _imgv2.layer.bordercolor = [Uicolor Orangecolor].
  Cgcolor;
  
  
  [Self.view Addsubview:_imgv2];
  [Self BINDPAN:_IMGV];
  [Self BINDPINCH:_IMGV];
  [Self BINDROTATION:_IMGV];
  [Self BINDTAP:_IMGV];
  
  [Self BINDLONGPRESS:_IMGV];
  [Self bindpan:_imgv2];
  [Self bindpinch:_imgv2];
  [Self bindrotation:_imgv2];
  [Self bindtap:_imgv2];
  
  [Self bindlongpress:_imgv2];
  To handle gesture recognition priorities, it is necessary to bind a custom tickle gesture [self bingcustomgesturerecognizer] first.
 [Self bindswipe];

 } @end

The above code is about iOS gesture operation (drag, kneading, rotation, click, long Press, light Sweep, custom) of the detailed, I hope to help.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.