在某些特殊情境下,需要針對螢幕旋轉做特殊處理。在 iOS 系統下實作相關功能相當方便,以下介紹兩種常見方法。
此通知監聽的是狀態列(StatusBar)的方向,與版面配置相關——只有當你的版面真的旋轉時才會收到通知,而非單純的裝置旋轉。
// 於 viewDidLoad 中註冊
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(statusBarOrientationChange:)
name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
- (void)statusBarOrientationChange:(NSNotification *)notification
{
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
if (orientation == UIInterfaceOrientationLandscapeRight) { /* home 鍵靠右 */ }
if (orientation == UIInterfaceOrientationLandscapeLeft) { /* home 鍵靠左 */ }
if (orientation == UIInterfaceOrientationPortrait) { /* 直向 */ }
if (orientation == UIInterfaceOrientationPortraitUpsideDown) { /* 倒置 */ }
}
當你關注的對象與版面配置相關、而非純粹的裝置旋轉時,適合採用這種方案。
此通知反映的是裝置本身的物理方向,包含朝上、朝下等狀態。
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(orientChange:)
name:UIDeviceOrientationDidChangeNotification object:nil];
- (void)orientChange:(NSNotification *)noti
{
UIDeviceOrientation orient = [UIDevice currentDevice].orientation;
/*
UIDeviceOrientationUnknown
UIDeviceOrientationPortrait // 直立,home 鍵在下
UIDeviceOrientationPortraitUpsideDown // 直立,home 鍵在上
UIDeviceOrientationLandscapeLeft // 橫放,home 鍵在右
UIDeviceOrientationLandscapeRight // 橫放,home 鍵在左
UIDeviceOrientationFaceUp // 平放,正面朝上
UIDeviceOrientationFaceDown // 平放,正面朝下
*/
switch (orient) {
case UIDeviceOrientationPortrait: break;
case UIDeviceOrientationLandscapeLeft: break;
case UIDeviceOrientationPortraitUpsideDown:break;
case UIDeviceOrientationLandscapeRight: break;
default: break;
}
}
由於這種方式的方向完全來自裝置的物理朝向,當你關注的只是物理方向時,通常註冊此通知來解決。(另外還有加速計 API 可實作類似功能,但它較底層,若上述兩法能解決問題則不建議使用,因為使用不當會造成很大的效能損耗。)