UIGestureRecognizer 是自 iOS 3.2 開始加入的手指動態辨識功能,本文所介紹的手指動態是橫向劃過螢幕的 UISwipeGestureRecognizer class。我們將利用手指由右至左,劃過螢幕的方式當做觸發事件,然後切換兩個不同的 View。(View-based Template)
在 Project 中的 ViewController 我們將他當做一個可以包含兩個 View 並切換的容器,然後再 Class 資料夾中另外加入兩個 ViewController 並且附帶 xib 檔。接著在最原先的ViewController.h 檔案中,宣告另外兩個 ViewController 當做它的 Instance Variable 並在程式進入點鍵入下列程式碼。
- (void)viewDidLoad { //宣告第一個viewcontroller //並加入到主要的viewcontroller也就是self的view中 NumberOneViewController *aViewController = [[NumberOneViewController alloc] init]; self.firstViewController = aViewController; [self.view addSubview:firstViewController.view]; [aViewController release]; //宣告第二個view controller放到記憶體中 //但是不加到主要的viewcontroller中 NumberTwoViewController *tempoViewController = [[NumberTwoViewController alloc] init]; self.secondViewController = tempoViewController; [tempoViewController release]; //宣告UISwipeGestureRecognizer同時指定target及action UISwipeGestureRecognizer *swipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(switchViews)]; //指定偵測手指劃過螢幕的方向為由右至左 swipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft; //加入swipe gesture recognizer到主要的viewcontroller中 [self.view addGestureRecognizer:swipeGestureRecognizer]; [swipeGestureRecognizer release]; [super viewDidLoad]; }
在宣告 UISwipeGestureRecognizer 時必須指定觸發事件後的反應對象以及方法。之後我們建立一個 switchViews 的方法來做兩個 View 的切換,其程式碼如下。
-(void)switchViews{ //設定兩個View切換時的過場動畫條件 [UIView beginAnimations:@"flipTransition" context:NULL]; [UIView setAnimationDuration:1.5]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; //條件式中設定兩個view之間的切換 if (self.secondViewController.view.superview == nil) { UIView *theSuperView = firstViewController.view.superview; [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:theSuperView cache:YES]; [firstViewController.view removeFromSuperview]; [theSuperView addSubview:secondViewController.view]; [UIView commitAnimations]; } else { UIView *theSuperView = secondViewController.view.superview; [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:theSuperView cache:YES]; [secondViewController.view removeFromSuperview]; [theSuperView addSubview:firstViewController.view]; [UIView commitAnimations]; } }
加入 GestureRecoginzer 的方式很簡單,但是要注意的是必須加到你要觸發事件的最上層的 View 也就是 superview 中,不然就是兩個 subview 都加入 GestureRecognizer,最方便的方式還是在 superview 中加入,然後利用 superview 觸發事件來做兩個 subview 的切換。結果就如同影片所示。
沒有留言:
張貼留言