一、有哪些手勢?
1.1、一次性手勢
Tap: 點擊 Swipe:輕掃
1.2、連續(xù)性手勢
LongPress: 長按 Pan:拖動 Pinch:捏合,擴張 Rotation: 旋轉(zhuǎn)
1.3、手勢的本質(zhì)
系統(tǒng)將用戶針對屏幕的物理性動作,轉(zhuǎn)換成數(shù)據(jù)儲存起來,這個數(shù)據(jù)就是封裝的對象,所以手勢這種物理性的操作最后都是一個一個的對象
二、如何使用手勢
step1:創(chuàng)建具體的手勢對象
step2:指定發(fā)生具體手勢時,響應(yīng)的方法
step3:設(shè)置手勢對象的常用屬性
step4:將手勢對象與具體的某個view關(guān)聯(lián)起來
2.1、UITapGestureRecognizer
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapmethod:)];
tap.numberOfTouchesRequired = 2;//點擊出點需要幾個點
tap.numberOfTapsRequired = 2;//連續(xù)點擊幾次才能引發(fā)手勢事件
//上面兩個參數(shù)默認(rèn)不寫的時候,系統(tǒng)默認(rèn)是1;
[self.view addGestureRecognizer:tap];
//如何判斷點擊的地方是在視圖的什么地方?
//在tap引發(fā)的時間中傳入的UIGestureRecognizer 有一個方法:[tap locationInView:tpbview];
//這個方法可以得到一個CGPoint, 雙指頭點擊的時候這個方法是無效的,因為無論點擊哪里得到的都是同一個CGPoint
2.2、UISwipeGestureRecognizer
- (void)viewDidLoad {
[super viewDidLoad];
UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipemethod:)];
swipe.direction = UISwipeGestureRecognizerDirectionLeft| UISwipeGestureRecognizerDirectionRight;
}
-(void)swipemethod:(UIGestureRecognizer *)swipe{
NSLog(@"123");
}
2.3、UILongPressGestureRecognizer
- (void)viewDidLoad {
[super viewDidLoad];
UILongPressGestureRecognizer *LongPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(LongPressmethod:)];
LongPress.minimumPressDuration = 2;
[self.view addGestureRecognizer: LongPress];
}
-(void) LongPressmethod:(UIGestureRecognizer *) LongPress{
if (LongPress.state == UIGestureRecognizerStateBegan) {
NSLog(@"began");
}else if (LongPress.state == UIGestureRecognizerStateChanged){
NSLog(@"change");
}else if (LongPress.state == UIGestureRecognizerStateEnded){
NSLog(@"end");
}
CGPoint point = [LongPress locationInView:self.view];
NSLog(@"%@",NSStringFromCGPoint(point));
}
//長按方法在長按時長達到時間后,執(zhí)行一次,抬起的時候也執(zhí)行一次
2.4、UIPanGestureRecognizer
- (void)viewDidLoad {
[super viewDidLoad];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[self.view addGestureRecognizer:pan];
}
-(void)pan:(UIPanGestureRecognizer *)pan{
//當(dāng)前位置
CGPoint point = [pan locationInView:self.view];
//相對于一開始按下的位置的位移
CGPoint point2 = [pan translationInView:self.view];
NSLog(@"point1:%@",NSStringFromCGPoint(point));
NSLog(@"point2:%@",NSStringFromCGPoint(point2));
}
2.5、UIPinchGestureRecognizer
- (void)viewDidLoad {
[super viewDidLoad];
UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinch:)];
[self.view addGestureRecognizer:pinch];
}
- (void)pinch:(UIPinchGestureRecognizer *)pin{
CGFloat velocity = pin.velocity;//捏合或者擴展的速度快慢
CGFloat scale = pin.scale;//捏合的動作比例
NSLog(@"velocity = %lf",velocity);
NSLog(@"scale = %lf",scale);
}