手勢在iOS開發中是一個比較常用的功能,不過相對來說大家用的比較少,經常刷網易新聞,上次用了一下捏合手勢才發現可以調整字體大小。昨天看到一個介紹搖一搖這個功能的,沒看到之前一直都覺得搖一搖是微信的專有的,昨天測試了一下知乎,感覺像發現了一個新大陸,隨便截了圖,效果如下:
扯的有點遠了,很多應用的很多功能其實對於大多數而言是沒有用到的,不過作為程序員我們還是應該多研究一下。
基礎概念
常見的手勢有六種,如下圖所示:
UITapGestureRecognizer(點擊,輕觸摸)、UIPinchGestureRecognizer(二指往內或往外撥動,捏合手勢)、UIPanGestureRecognizer(拖移)、UISwipeGestureRecognizer(滑動,快速移動)、UIRotationGestureRecognizer(旋轉)和UILongPressGestureRecognizer(長按),由於微信的緣故應該大多數人對長按比較熟悉,Tap點擊也是高頻用到的手勢。
蘋果官方給出了Tap和Pinch的手勢的效果圖,其他的效果可以私下試一試:
Demo實戰
由於有六種手勢,基本上大同小異,其中一種會實戰,其他的應該也沒問題,接下來的的介紹都是以UITapGestureRecognizer為基准的,先來個簡單的單擊手勢:
UITapGestureRecognizer *oneTapGestureReognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(oneTapGestureRecognizer:)]; oneTapGestureReognizer.delegate = self; oneTapGestureReognizer.numberOfTapsRequired = 1;//觸摸次數 [self.view addGestureRecognizer:oneTapGestureReognizer];
響應事件:
-(void)oneTapGestureRecognizer:(UITapGestureRecognizer *)tapGestureRecognizer{ UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"單指單擊" message:@"iOS技術交流群:228407086" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:@"取消", nil]; [alertView show]; }
效果如下:
單擊手勢顯得稍微有點弱,我們可以繼續修改手指和觸摸的次數,來個雙指雙擊看下代碼:
UITapGestureRecognizer *twoTapGestureReognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(twoTapGestureRecognizer:)]; twoTapGestureReognizer.delegate = self; twoTapGestureReognizer.numberOfTouchesRequired =2;//手指數 twoTapGestureReognizer.numberOfTapsRequired=2;//觸摸次數 [self.view addGestureRecognizer:twoTapGestureReognizer];
響應事件如下:
-(void)twoTapGestureRecognizer:(UITapGestureRecognizer *)tapGestureRecognizer{ UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"手勢點擊" message:@"iOS技術交流群:228407086" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:@"取消", nil]; [alertView show]; }
效果就不需要截圖了,基本上UITapGestureRecognizer點擊差不多就是設置一下手指數量和觸摸次數,不過有的時候會出現同一個View上需要手勢,按鈕需要點擊,就是事件被覆蓋,需要通過UIGestureRecognizerDelegate中的方法防止事件覆蓋。
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{ //設置為NO則不響應 if ([NSStringFromClass([touch.view class]) isEqualToString:@"UILabel"]) { return NO; } return YES; }
上面的代碼是為了讓截圖上的標簽不響應觸摸的事件,標簽其實默認的是沒有點擊響應事件的,我們可以在標簽上面加入觸摸事件:
UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(10, 44, 380, 30)]; label.text=@"原文地址:http://www.cnblogs.com/xiaofeixiang"; [label setUserInteractionEnabled:YES]; [label addGestureRecognizer:tapGestureRecognizer]; [self.view addSubview:label];
響應事件:
-(void)tapJumpLink:(UITapGestureRecognizer *)tapGestureRecognizer{ UILabel *label=(UILabel *)tapGestureRecognizer.view; NSURL *url=[[NSURL alloc]initWithString:[label.text substringFromIndex:5]]; [[UIApplication sharedApplication] openURL:url]; }
最終效果如下:
附贈iOS技術交流群:228407086,如果關於博客或者iOS有什么問題,歡迎入群討論~