Gesture operations for IOS Learning

Source: Internet
Author: User

Gesture operations for IOS Learning
1. UIGestureRecognizer Introduction The UIGestureRecognizer class is an abstract class. The following sub-classes are specific gestures, which can be directly used for Gesture Recognition. UITapGestureRecognizer // click rotate // the second finger to move inside or out. The scaling UIRotationGestureRecognizer is usually used to rotate the slider // slide to quickly move UIPanGestureRecognizer, slow move UILongPressGestureRecognizer // long press 2. Using gestures is very simple. There are two steps: (1) creating a gesture instance. When creating a gesture, specify a callback method. When the gesture starts, changes, or ends, the callback method is called. (2) Add it to the View to be recognized. Each gesture corresponds to only one View. When the screen is touched within the View boundary, if the gesture is the same as the predefined one, the method will be called back. Ps: A gesture can only correspond to one View, but a View can have multiple gestures. 3. Pan drag gesture:

// Create an ImageView, and then add the gesture UIImageView * snkeimageview = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @ "Snail ke.png. frame = CGRectMake (50, 50,100,160); optional * panGestureRecognizer = [[using alloc] initWithTarget: self action: @ selector (handlePan :)]; [snkeimageview failed: Failed]; [self. view setBackgroundColor: [UIColor whiteColor]; [self. view addSubview: snkeimageview]; // callback method:-(void) handlePan :( UIPanGestureRecognizer *) recognizer {CGPoint translation = [recognizer translationInView: self. view]; recognizer. view. center = CGPointMake (recognizer. view. center. x + translation. x, recognizer. view. center. y + translation. y); [recognizer setTranslation: CGPointZero inView: self. view];}

 

4. Pinch scaling gesture
UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc]                                                          initWithTarget:self                                                          action:@selector(handlePinch:)];                                                         - (void) handlePinch:(UIPinchGestureRecognizer*) recognizer  {      recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);      recognizer.scale = 1;  }

 

5. Rotation gesture
UIRotationGestureRecognizer *rotateRecognizer = [[UIRotationGestureRecognizer alloc]                                                   initWithTarget:self                                                   action:@selector(handleRotate:)];  [snakeImageView addGestureRecognizer:rotateRecognizer];- (void) handleRotate:(UIRotationGestureRecognizer*) recognizer  {      recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform, recognizer.rotation);      recognizer.rotation = 0;  }

 

6. Add the second ImagView and gesture. Remember: A gesture can only be added to one View. Of course, two views must have two gesture instances.
- (void)viewDidLoad  {      [super viewDidLoad];        UIImageView *snakeImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"snake.png"]];      UIImageView *dragonImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dragon.png"]];      snakeImageView.frame = CGRectMake(120, 120, 100, 160);      dragonImageView.frame = CGRectMake(50, 50, 100, 160);      [self.view addSubview:snakeImageView];      [self.view addSubview:dragonImageView];        for (UIView *view in self.view.subviews) {          UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]                                                          initWithTarget:self                                                          action:@selector(handlePan:)];            UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc]                                                              initWithTarget:self                                                              action:@selector(handlePinch:)];            UIRotationGestureRecognizer *rotateRecognizer = [[UIRotationGestureRecognizer alloc]                                                           initWithTarget:self                                                           action:@selector(handleRotate:)];            [view addGestureRecognizer:panGestureRecognizer];          [view addGestureRecognizer:pinchGestureRecognizer];          [view addGestureRecognizer:rotateRecognizer];          [view setUserInteractionEnabled:YES];      }      [self.view setBackgroundColor:[UIColor whiteColor]];       }

 

7. How to Achieve the speed of dragging (pan gesture) (view sliding effect after dragging and dropping at a fast speed? 1. monitor whether the gesture ends 2. Monitor the touch speed
- (void) handlePan:(UIPanGestureRecognizer*) recognizer  {      CGPoint translation = [recognizer translationInView:self.view];      recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,                                         recognizer.view.center.y + translation.y);      [recognizer setTranslation:CGPointZero inView:self.view];        if (recognizer.state == UIGestureRecognizerStateEnded) {            CGPoint velocity = [recognizer velocityInView:self.view];          CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));          CGFloat slideMult = magnitude / 200;          NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);            float slideFactor = 0.1 * slideMult; // Increase for more of a slide          CGPoint finalPoint = CGPointMake(recognizer.view.center.x + (velocity.x * slideFactor),                                           recognizer.view.center.y + (velocity.y * slideFactor));          finalPoint.x = MIN(MAX(finalPoint.x, 0), self.view.bounds.size.width);          finalPoint.y = MIN(MAX(finalPoint.y, 0), self.view.bounds.size.height);            [UIView animateWithDuration:slideFactor*2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{              recognizer.view.center = finalPoint;          } completion:nil];      }

 

Code Implementation parsing: 1. The length of the compute speed vector (probably mostly forgotten. 2. if the velocity vector is less than 200, a decimal point is obtained, and the slide is very short. calculate an endpoint Based on velocity and velocity. 4. make sure that the end does not run out of the parent View boundary 5. after you use the UIView animation to move the view to the end, you can drag the Image view to open the view and see that the view slides in the original direction. 8. gesture gestures that trigger two views at the same time are mutually exclusive. If you want to trigger views of both snakes and dragons, You need to implement the UIGestureRecognizerDelegate protocol and return YES in the Protocol method.
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {      return YES;  }

 

Set self as proxy to gesture:
panGestureRecognizer.delegate = self;  pinchGestureRecognizer.delegate = self;  rotateRecognizer.delegate = self;

 

In this way, you can drag or rotate two views at the same time. 19. Click the tap gesture to show the effect of the tap. When you click the screen, play a sound. To play the sound, we add the AVFoundation. framework.
- (AVAudioPlayer *)loadWav:(NSString *)filename {      NSURL * url = [[NSBundle mainBundle] URLForResource:filename withExtension:@"wav"];      NSError * error;      AVAudioPlayer * player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];      if (!player) {          NSLog(@"Error loading %@: %@", url, error.localizedDescription);      } else {          [player prepareToPlay];      }      return player;  }

 

I will provide the complete code in the final example code. The steps for adding gestures are the same as those described above.
#import <UIKit/UIKit.h>  #import <AVFoundation/AVFoundation.h>  @interface ViewController : UIViewController<UIGestureRecognizerDelegate>  @property (strong) AVAudioPlayer * chompPlayer;  @property (strong) AVAudioPlayer * hehePlayer;  @end  - (void)handleTap:(UITapGestureRecognizer *)recognizer {      [self.chompPlayer play];  }

 

Run. Click a picture to play a bit. However, this click playback sound is a bit defective, that is, it will be played when you drag it slowly. This makes the two gestures overlap. How can this problem be solved? Use the requireGestureRecognizerToFail method of the gesture. 10. Add this code in the viewDidLoad loop for gesture dependencies: 1 [tapRecognizer requireGestureRecognizerToFail: panGestureRecognizer]; that is, if the pan gesture fails, it is not dragged, to start the tap gesture. In this case, if you drag the image slightly, the pan gesture occurs. The tap sound will not sound. 11. Custom gesture custom gesture inheritance: UIGestureRecognizer. The following method is implemented:
– touchesBegan:withEvent:  – touchesMoved:withEvent:  – touchesEnded:withEvent:  - touchesCancelled:withEvent:

 

Create a new class that inherits UIGestureRecognizer. The Code is as follows:. h file
#import <UIKit/UIKit.h>  typedef enum {      DirectionUnknown = 0,      DirectionLeft,      DirectionRight  } Direction;    @interface HappyGestureRecognizer : UIGestureRecognizer  @property (assign) int tickleCount;  @property (assign) CGPoint curTickleStart;  @property (assign) Direction lastDirection;    @end

 

. M file
# Import "HappyGestureRecognizer. h "# import <UIKit/UIGestureRecognizerSubclass. h> # define REQUIRED_TICKLES 2 # define runtime 25 @ implementation runtime-(void) touchesBegan :( NSSet *) touches withEvent :( UIEvent *) event {UITouch * touch = [touches anyObject]; self. curTickleStart = [touch locationInView: self. view];}-(void) touchesMoved :( NSSet *) touches withEvent :( UIEvent *) Event {// Make sure we 've moved a minimum amount since curTickleStart UITouch * touch = [touches anyObject]; CGPoint ticklePoint = [touch locationInView: self. view]; CGFloat moveAmt = ticklePoint. x-self. curTickleStart. x; Direction curDirection; if (moveAmt <0) {curDirection = direleft left;} else {curDirection = DirectionRight;} if (ABS (moveAmt) <MOVE_AMT_PER_TICKLE) return; // confirm that the direction has changed if (Self. lastDirection = DirectionUnknown | (self. lastDirection = DirectionLeft & curDirection = DirectionRight) | (self. lastDirection = DirectionRight & curDirection = direleft left) {// self. tickleCount ++; self. curTickleStart = ticklePoint; self. lastDirection = curDirection; // if the number of scratching attempts exceeds the specified number, set the gesture to the end state. // The callback function will be called. If (self. state = UIGestureRecognizerStatePossible & self. tickleCount> REQUIRED_TICKLES) {[self setState: UIGestureRecognizerStateEnded] ;}}- (void) reset {self. tickleCount = 0; self. curTickleStart = CGPointZero; self. lastDirection = DirectionUnknown; if (self. state = UIGestureRecognizerStatePossible) {[self setState: Unknown];}-(void) touchesEnded :( NSSet *) touches withEvent :( UIEvent *) event {[self reset];} -(void) touchesCancelled :( NSSet *) touches withEvent :( UIEvent *) event {[self reset];} @ end

 

The call of a custom gesture is the same as the above, and the write is returned as follows:
- (void)handleHappy:(HappyGestureRecognizer *)recognizer{      [self.hehePlayer play];  }

 

After the gesture is successful, the sound of laughter is played. Run on the real machine, hold down a view, and drag left and right to make a smile. Code parsing: first obtain the starting coordinate: curTickleStart compares with the x value of ticklePoint to determine whether the current put-down is left or right. Then, determine whether the moving x value is longer than MOVE_AMT_PER_TICKLE. If it is too large, return. Determine whether three actions are performed in different directions. If yes, the gesture ends and the callback is performed.

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.