2015-03-02 252 views
7

我使用viewWillTransitionToSize來檢測設備何時旋轉到橫向。根據目標的大小,我能檢測是否景觀朝向,並根據需要調整自己的特質......iOS viewWillTransitionToSize和設備方向

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { 

    if size.width > size.height { 
     self.setOverrideTraitCollection(UITraitCollection(horizontalSizeClass: UIUserInterfaceSizeClass.Regular), forChildViewController: viewController) 
    } 
    else{ 
     self.setOverrideTraitCollection(nil, forChildViewController: viewController) 
    } 

    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) 
} 

不過,我希望能夠檢測我的設備是否正在轉換爲橫向向左或landscape-對。這將允許我創建不同的行爲或視圖,具體取決於設備的特定方向。 (左還是右)。

這可能沒有使用任何棄用的功能?

我想用狀態欄方向......

let orientation = UIApplication.sharedApplication().statusBarOrientation; 
    if(orientation == UIInterfaceOrientation.LandscapeLeft) 
    { 
     // Do something 
    } 
    else if(orientation == UIInterfaceOrientation.LandscapeRight) 
    { 
     // Do something else 
    } 

......但這並沒有幫助,因爲這似乎給「老」的狀態取向。

我該如何獲得具體的目標定位?

回答

0

使用[UIDevice currentDevice].orientation

6

同時旋轉使用UIViewControllerTransitionCoordinator,你可以得到方向如下:

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

    // will execute before rotation 

    coordinator.animate(alongsideTransition: { (context: UIViewControllerTransitionCoordinatorContext) in 

     // will execute during rotation 
     let orientation = UIApplication.shared.statusBarOrientation 
     if orientation == .landscapeLeft 
     { 
      // Do something 
     } 
     else if orientation == .landscapeRight 
     { 
      // Do something else 
     } 
    }) { (context: UIViewControllerTransitionCoordinatorContext) in 
     // will execute after rotation 
    } 
}