2013-07-28 25 views
1

我有一個簡單的if語句來檢測方向並執行一個操作。這很有效,但它只在第一次運行,並且無法再檢測到。如何在ios中執行連續方向檢測?

這個void只會被調用一次嗎?如果是這樣,我該如何改變這個常常檢查?

我需要移動一些到viewDidLoad

- (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration 
    { 
     [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration]; 

     if (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) 

     { 
      [self.navigationController pushViewController:graphView animated:YES]; 

     } 

      else if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) 
      { 
       [self.navigationController pushViewController:graphView animated:YES]; 
      } 

      else if (toInterfaceOrientation == UIInterfaceOrientationPortrait) 
      { 
       [self.navigationController popToRootViewControllerAnimated:YES]; 
       NSLog(@"portrait"); 
      } 

      else 
      { 
       [self.navigationController popToRootViewControllerAnimated:YES]; 

      } 

     } 
+0

你想完成什麼? –

+0

我試圖根據方向使用UINavigationController在視圖控制器之間來回切換 –

+0

此代碼位於導航控制器中還是位於導航控制器中的視圖控制器中? – user

回答

1
[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(orientationChanged:) 
              name:@"UIDeviceOrientationDidChangeNotification" 
              object:nil]; 
+0

是否可以在視圖中加載,然後在orientationChanged方法中創建if語句以檢測確切的方向? –

1

簡釋什麼@Vjy wrote- 一種解決方案是監聽設備方向的通知,然後找到新的方向,並對此作出迴應。

得到任何設備的方向通知雖然之前,你必須電話

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; 

或不通知將在第一時間發送。開始生成方向通知後,您必須聽取它們。 你需要告訴每個相關視圖控制器

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(orientationDetected) //this is your function 
              name:@"UIDeviceOrientationDidChangeNotification" 
              object:nil]; 

然後orientationDetected監聽這些通知或任何你想說出它 -

- (void) orientationDetected 
{ 
    switch ([[UIDevice currentDevice] orientation]) 
    { 
     case UIDeviceOrientationLandscapeLeft: 
      // push appropriate view controller 
      break; 

     case UIDeviceOrientationPortrait: 
      // and so on... 
      break; 
    } 
} 

您還可以更改您的通知選擇方法@selector(methodThatReceivesNote:)(注意冒號),並讓你的方法採用(NSNotification*)參數,然後通過[paramName userInfo]查找相關的方向,儘管我發現有關UIDevice通知實際包含的信息很少。userInfo

您也可以研究如何在導航控制器的子視圖中處理設備方向更改。我環視了一下,但我無法真正發現這件事。我確定這些信息在某處,這可能是比通知更強大的解決方案。