一、UIGestureRecognizer介紹
手勢識別在iOS上很是重要,手勢操做移動設備的重要特徵,極大的增長了移動設備使用便捷性。
iOS系統在3.2之後,爲方便開發這使用一些經常使用的手勢,提供了UIGestureRecognizer類。手勢識別UIGestureRecognizer類是個抽象類,下面的子類是具體的手勢,開發這能夠直接使用這些手勢識別。
- Tap(點一下)
- Pinch(二指往內或往外撥動,平時常常用到的縮放)
- Rotation(旋轉)
- Swipe(滑動,快速移動)
- Pan (拖移,慢速移動)
- LongPress(長按)
UIGestureRecognizer的繼承關係以下:
二、使用手勢的步驟
使用手勢很簡單,分爲兩步:
- 建立手勢實例。當建立手勢時,指定一個回調方法,當手勢開始,改變、或結束時,回調方法被調用。
- 添加到須要識別的View中。每一個手勢只對應一個View,當屏幕觸摸在View的邊界內時,若是手勢和預約的同樣,那就會回調方法。
ps:一個手勢只能對應一個View,可是一個View能夠有多個手勢。
建議在真機上運行這些手勢,模擬器操做不太方便,可能致使你認爲手勢失效。
三、Pan 拖動手勢:
- UIImageView *snakeImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"snake.png"]];
- snakeImageView.frame = CGRectMake(50, 50, 100, 160);
- UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]
- initWithTarget:self
- action:@selector(handlePan:)];
- [snakeImageView addGestureRecognizer:panGestureRecognizer];
- [self.view setBackgroundColor:[UIColor whiteColor]];
- [self.view addSubview:snakeImageView];
新建一個ImageView,而後添加手勢
回調方法:
- - (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];
-
- }
四、Pinch縮放手勢
- UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc]
- initWithTarget:self
- action:@selector(handlePinch:)];<p class="p1">[<span class="s1">snakeImageView</span> <span class="s2">addGestureRecognizer</span>:pinchGestureRecognizer];</p>
- - (void) handlePinch:(UIPinchGestureRecognizer*) recognizer
- {
- recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);
- recognizer.scale = 1;
- }
五、Rotation旋轉手勢
- 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;
- }
添加了這幾個手勢後,運行看效果,程序中的imageView放了一個
/^\/^\
_|__| O|
\/ /~ \_/ \
\____|__________/ \
\_______ \
`\ \ \
| | \
/ / \
/ / \\
/ / \ \
/ / \ \
/ / _----_ \ \
/ / _-~ ~-_ | |
( ( _-~ _--_ ~-_ _/ |
\ ~-____-~ _-~ ~-_ ~-_-~ /
~-_ _-~ ~-_ _-~
~--______-~ ~-___-~
的圖片,在模擬器上拖動是沒問題的。縮放和旋轉有點問題,估計是由於在模擬器上的模擬的兩個接觸點距離在imageView的邊界外了,因此操做無效果。
建議在真機上運行這個手勢。
在模擬器上縮放和選擇的操做技巧:
能夠把imageView的frame值設置大一點,按住alt鍵,按下觸摸板(不按下不行),這樣就能夠旋轉和縮放了。
六、添加第二個ImagView並添加手勢
記住:一個手勢只能添加到一個View,兩個View固然要有兩個手勢的實例了
- - (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]];
- }
多添加了一條龍的view,兩個view都能接收上面的三種手勢。運行效果以下:
七、拖動(pan手勢)速度(以較快的速度拖放後view有滑行的效果)
如何實現呢?
- - (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;
- 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];
-
- }
-
代碼實現解析:
- 計算速度向量的長度(估計大部分都忘了)這些知識了。
- 若是速度向量小於200,那就會獲得一個小於的小數,那麼滑行會很短
- 基於速度和速度因素計算一個終點
- 確保終點不會跑出父View的邊界
- 使用UIView動畫使view滑動到終點
運行後,快速拖動圖像view
放開會看到view還會在原來的方向滑行一段路。
八、同時觸發兩個view的手勢
手勢之間是互斥的,若是你想同時觸發蛇和龍的view,那麼須要實現協議
UIGestureRecognizerDelegate,html
- @interface ViewController : UIViewController<UIGestureRecognizerDelegate>
- @end
並在協議這個方法裏返回YES。
- -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
- {
- return YES;
- }
把self做爲代理設置給手勢:
- panGestureRecognizer.delegate = self;
- pinchGestureRecognizer.delegate = self;
- rotateRecognizer.delegate = self;
這樣能夠同時拖動或旋轉縮放兩個view了。
九、tap點擊手勢
這裏爲了方便看到tap的效果,當點擊一下屏幕時,播放一個聲音。ios
爲了播放聲音,咱們加入AVFoundation.framework這個框架。app
- - (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;
- }
我會在最後例子代碼給出完整代碼,添加手勢的步驟和前面同樣的。
- #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];
- }
運行,點一下某個圖,就會播放一個咬東西的聲音。框架
不過這個點擊播放聲音有點缺陷,就是在慢慢拖動的時候也會播放。這使得兩個手勢重合了。怎麼解決呢?使用手勢的:requireGestureRecognizerToFail方法。ide
十、手勢的依賴性
在viewDidLoad的循環裏添加這段代碼:函數
- [tapRecognizer requireGestureRecognizerToFail:panGestureRecognizer];
意思就是,當若是pan手勢失敗,就是沒發生拖動,纔會出發tap手勢。這樣若是你有輕微的拖動,那就是pan手勢發生了。tap的聲音就不會發出來了。
十一、自定義手勢
自定義手勢繼承:UIGestureRecognizer,實現下面的方法:動畫
- – touchesBegan:withEvent:
- – touchesMoved:withEvent:
- – touchesEnded:withEvent:
- - touchesCancelled:withEvent:
新建一個類,繼承UIGestureRecognizer,代碼以下:ui
.h文件url
- #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文件
- #import "HappyGestureRecognizer.h"
- #import <UIKit/UIGestureRecognizerSubclass.h>
- #define REQUIRED_TICKLES 2
- #define MOVE_AMT_PER_TICKLE 25
-
- @implementation HappyGestureRecognizer
-
- - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
- UITouch * touch = [touches anyObject];
- self.curTickleStart = [touch locationInView:self.view];
- }
-
- - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
-
-
- UITouch * touch = [touches anyObject];
- CGPoint ticklePoint = [touch locationInView:self.view];
- CGFloat moveAmt = ticklePoint.x - self.curTickleStart.x;
- Direction curDirection;
- if (moveAmt < 0) {
- curDirection = DirectionLeft;
- } else {
- curDirection = DirectionRight;
- }
- if (ABS(moveAmt) < MOVE_AMT_PER_TICKLE) return;
-
-
- if (self.lastDirection == DirectionUnknown ||
- (self.lastDirection == DirectionLeft && curDirection == DirectionRight) ||
- (self.lastDirection == DirectionRight && curDirection == DirectionLeft)) {
-
-
- self.tickleCount++;
- self.curTickleStart = ticklePoint;
- self.lastDirection = curDirection;
-
-
-
- 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:UIGestureRecognizerStateFailed];
- }
- }
-
- - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
- {
- [self reset];
- }
-
- - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
- {
- [self reset];
- }
-
- @end
調用自定義手勢和上面同樣,回到這樣寫:
- - (void)handleHappy:(HappyGestureRecognizer *)recognizer{
- [self.hehePlayer play];
- }
手勢成功後播放呵呵笑的聲音。
在真機上運行,按住某個view,快速左右拖動,就會發出笑的聲音了。
代碼解析:
先獲取起始座標:
curTickleStart
經過和
ticklePoint的x值對比,得出當前的放下是向左仍是向右。再算出移動的x的值是否比
MOVE_AMT_PER_TICKLE距離大,若是太則返回。
再判斷是否有三次是不一樣方向的動做,若是是則手勢結束,回調。
參考:http://www.raywenderlich.com/6567/uigesturerecognizer-tutorial-in-ios-5-pinches-pans-and-more