10

我正在製作一個需要在旋轉時進行一點界面重排的iOS應用程序。我正試圖通過執行- (void)orientationChanged:(NSNotification *)note來檢測此問題,但是這會告知我設備何時正面朝上或正面朝下。在iOS中檢測旋轉更改

我想要一種方式來當界面改變方向時得到通知。

回答

26

有幾種方法,你可以做到這一點,你可以在UIViewController class reference找到他們:

– willRotateToInterfaceOrientation:duration: 
– willAnimateRotationToInterfaceOrientation:duration: 
– didRotateFromInterfaceOrientation: 

你也能做到這一點的viewWillLayoutSubviews方法,但要小心,因爲它被稱爲上屏幕外觀,以及每當你添加一個子視圖。

編輯:

解決方案現在已經過時,見接受的答案。

+9

請注意,所有這三個都不推薦在iOS 8中使用。他們建議使用可以轉換爲大小的變體。 –

4

夫特3:

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

} 
1

從iOS 8開始,這是正確的方法。

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

    coordinator.animate(alongsideTransition: { context in 
     // This is called during the animation 
    }, completion: { context in 
     // This is called after the rotation is finished. Equal to deprecated `didRotate` 
    }) 
}