參考文章 http://blog.jobbole.com/65846/

1. UIGestureRecognizer介紹
UIGestureRecognizer類是個抽象類,下面的子類是具體的手勢,開發(fā)這可以直接使用這些手勢識別。
UITapGestureRecognizer // 點擊
UIPinchGestureRecognizer // 二指往內(nèi)或往外撥動,平時經(jīng)常用到的縮放
UIRotationGestureRecognizer // 旋轉(zhuǎn)
UISwipeGestureRecognizer // 滑動,快速移動
UIPanGestureRecognizer // 拖移,慢速移動
UILongPressGestureRecognizer // 長按
2、使用手勢的步驟
使用手勢很簡單,分為兩步:
(1)創(chuàng)建手勢實例。當(dāng)創(chuàng)建手勢時,指定一個回調(diào)方法,當(dāng)手勢開始,改變、或結(jié)束時,回調(diào)方法被調(diào)用。
(2)添加到需要識別的View中。每個手勢只對應(yīng)一個View,當(dāng)屏幕觸摸在View的邊界內(nèi)時,如果手勢和預(yù)定的一樣,那就會回調(diào)方法。
ps:一個手勢只能對應(yīng)一個View,但是一個View可以有多個手勢。
3、Pan 拖動手勢:
// 新建一個ImageView,然后添加手勢
UIImageView *snakeImageView = [[UIImageView alloc] initWithImage:[UIImage p_w_picpathNamed:@"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];
// 回調(diào)方法:
- (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縮放手勢
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旋轉(zhuǎn)手勢
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、添加第二個ImagView并添加手勢
記住:一個手勢只能添加到一個View,兩個View當(dāng)然要有兩個手勢的實例了
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *snakeImageView = [[UIImageView alloc] initWithImage:[UIImage p_w_picpathNamed:@"snake.png"]];
UIImageView *dragonImageView = [[UIImageView alloc] initWithImage:[UIImage p_w_picpathNamed:@"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、拖動(pan手勢)速度(以較快的速度拖放后view有滑行的效果)
如何實現(xiàn)呢?
1.監(jiān)視手勢是否結(jié)束
2.監(jiān)視觸摸的速度
- (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];
}代碼實現(xiàn)解析:
1.計算速度向量的長度(估計大部分都忘了)這些知識了。
2.如果速度向量小于200,那就會得到一個小于的小數(shù),那么滑行會很短
3.基于速度和速度因素計算一個終點
4.確保終點不會跑出父View的邊界
5.使用UIView動畫使view滑動到終點
運行后,快速拖動圖像view放開會看到view還會在原來的方向滑行一段路。
8、同時觸發(fā)兩個view的手勢
手勢之間是互斥的,如果你想同時觸發(fā)蛇和龍的view,那么需要實現(xiàn)協(xié)議UIGestureRecognizerDelegate,
并在協(xié)議這個方法里返回YES。
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}把self作為代理設(shè)置給手勢:
panGestureRecognizer.delegate = self; pinchGestureRecognizer.delegate = self; rotateRecognizer.delegate = self;
這樣可以同時拖動或旋轉(zhuǎn)縮放兩個view了。
9、tap點擊手勢
這里為了方便看到tap的效果,當(dāng)點擊一下屏幕時,播放一個聲音。
為了播放聲音,我們加入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;
}我會在最后例子代碼給出完整代碼,添加手勢的步驟和前面一樣的。
#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方法。
10、手勢的依賴性
在viewDidLoad的循環(huán)里添加這段代碼:
[tapRecognizer requireGestureRecognizerToFail:panGestureRecognizer];
意思就是,當(dāng)如果pan手勢失敗,就是沒發(fā)生拖動,才會出發(fā)tap手勢。這樣如果你有輕微的拖動,那就是pan手勢發(fā)生了。tap的聲音就不會發(fā)出來了。
11、自定義手勢
自定義手勢繼承:UIGestureRecognizer,實現(xiàn)下面的方法:
– touchesBegan:withEvent: – touchesMoved:withEvent: – touchesEnded:withEvent: - touchesCancelled:withEvent:
新建一個類,繼承UIGestureRecognizer,代碼如下:
.h文件
#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 {
// 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 = DirectionLeft;
} else {
curDirection = DirectionRight;
}
if (ABS(moveAmt) < MOVE_AMT_PER_TICKLE) return;
// 確認(rèn)方向改變了
if (self.lastDirection == DirectionUnknown ||
(self.lastDirection == DirectionLeft && curDirection == DirectionRight) ||
(self.lastDirection == DirectionRight && curDirection == DirectionLeft)) {
// 撓癢次數(shù)
self.tickleCount++;
self.curTickleStart = ticklePoint;
self.lastDirection = curDirection;
// 一旦撓癢次數(shù)超過指定數(shù),設(shè)置手勢為結(jié)束狀態(tài)
// 這樣回調(diào)函數(shù)會被調(diào)用。
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調(diào)用自定義手勢和上面一樣,回到這樣寫:
- (void)handleHappy:(HappyGestureRecognizer *)recognizer{
[self.hehePlayer play];
}手勢成功后播放呵呵笑的聲音。
在真機上運行,按住某個view,快速左右拖動,就會發(fā)出笑的聲音了。
代碼解析:
先獲取起始坐標(biāo):curTickleStart
通過和ticklePoint的x值對比,得出當(dāng)前的放下是向左還是向右。再算出移動的x的值是否比MOVE_AMT_PER_TICKLE距離大,如果太則返回。
再判斷是否有三次是不同方向的動作,如果是則手勢結(jié)束,回調(diào)。
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
網(wǎng)站欄目:IOS學(xué)習(xí)之手勢操作-創(chuàng)新互聯(lián)
文章URL:http://chinadenli.net/article28/hgjcp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計、建站公司、品牌網(wǎng)站制作、網(wǎng)站改版、標(biāo)簽優(yōu)化、虛擬主機
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容