2014-09-05 16 views
1

我的應用程序使用CMMotionManager來跟蹤設備運動,但iOS總是以標準設備方向(底部的主頁按鈕)返回設備運動數據。如何在iOS 8下調整CMMotionManager數據的方向?

要獲得運動數據轉換成相同的方向我UIView,我積累的觀點,從我的觀點轉變到窗口是這樣的:

CGAffineTransform transform = self.view.transform; 
for (UIView *superview = self.view.superview; superview; superview = superview.superview) { 
    CGAffineTransform superviewTransform = superview.transform; 
    transform = CGAffineTransformConcat(transform, superviewTransform); 
} 

這個轉換得到正確下的iOS 6 & 7計算,但iOS 8更改了旋轉模型,現在無論設備如何定向,視圖總是返回標識變換(不旋轉)。儘管如此,運動管理器的數據仍然以標準方向固定。

監控UIDevice旋轉通知並手動計算四個轉換似乎是在iOS 8下獲得此轉換的一種方法,但它也似乎不好,因爲設備方向不一定匹配我的視圖方向(即iPhone上的上通常不支持設備方向)。

將CMMotionManager的輸出轉化爲iOS 8下特定UIView的方向的最佳方式是什麼?

回答

0

我無法找到一個方法來直接計算變換,所以不是我改變了我的代碼來計算設定手動變換時willRotateToInterfaceOrientation:在我看來,控制器接收到的消息,像這樣:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { 
    CGAffineTransform transform; 
    switch (toInterfaceOrientation) { 
     case UIInterfaceOrientationLandscapeLeft: 
      transform = CGAffineTransformMake(
       0, -1, 
       1, 0, 
       0, 0); 
      break; 

     case UIInterfaceOrientationLandscapeRight: 
      transform = CGAffineTransformMake(
       0, 1, 
       -1, 0, 
       0, 0); 
      break; 

     case UIInterfaceOrientationPortraitUpsideDown: 
      transform = CGAffineTransformMake(
       -1, 0, 
       0, -1, 
       0, 0); 
      break; 

     case UIInterfaceOrientationPortrait: 
      transform = CGAffineTransformIdentity; 
      break; 
    } 
    self.motionTransform = transform; 
} 
1

儘管不是很明顯,但iOS 8和更高版本中推薦的方法是使用過渡協調器。

viewWillTransition(to:with:),協調可以傳給你一個實例採用在取其其方法的調用完成塊UIViewControllerTransitionCoordinatorContext(由UIKit中使用的默認協調人居然是自己的上下文,但這並不一定如此)。

上下文的targetTransform屬性是在動畫結束時應用到接口的旋轉。注意這是一個相對於的變換,而不是由此產生的絕對接口的變換。

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { 
    super.viewWillTransition(to: size, with: coordinator) 

    let animation: (UIViewControllerTransitionCoordinatorContext) -> Void = { context in 
     // your animation 
    } 

    coordinator.animate(alongsideTransition: animation) { context in 
     // store the relative rotation (or whatever you need to do with it) 
     self.transform = context.targetTransform 
    } 
} 

雖然老方法仍然有效,這個API是大概更符合蘋果的UI框架的未來發展方向行,它允許更大的靈活性,當你需要控制的動畫過渡。

+0

感謝您的深入瞭解 – 2016-07-22 19:53:38

+0

沒問題!希望能夠幫助其他人尋找相同的東西。 – 2016-07-22 21:14:18