2015年12月18日 星期五

iOS筆記:固定/判斷/旋轉裝置方向

裝置方向有四個:

直立:Portrait,PortraitUpsideDown
橫豎:LandscapeLeft,LandscapeRight


固定裝置:

在xcode打開traget設定,在General >  Deployment Info >  Device Orientation


取得目前裝置方向:

//第一種
//self.interfaceOrientation在iOS9的替代方法
[[UIApplication sharedApplication] statusBarOrientation];//returns UIInterfaceOrientation
//第二種
[[UIDevice currentDevice] orientation]; //returns UIDeviceOrientation

偵測裝置轉換方向:

判斷長寬差距可以知道螢幕是橫屏還直立的
//複寫此方法可以在螢幕旋轉時自動觸發
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<uiviewcontrollertransitioncoordinator>)coordinator
{
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    NSLog(@"NEW SIZE:(%f,%f)", size.width, size.height);
    if (size.width > size.height) {
        //orientation is landscape
        NSLog(@"orientation is landscape");
    }
    else{
        //orientation is Portrait
        NSLog(@"orientation is Portrait");
    }
}

用程式碼控制螢幕方向:

//(前提是target內device orientation 要允許旋轉(打勾))
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger: UIInterfaceOrientationPortrait]
                            forKey:@"orientation"];//轉成直立



參考資料:
iOS 8 Orientation Change Detection
Different ways of getting current interface orientation?
iOS9横竖屏设置的处理方法和实例讲解

沒有留言:

張貼留言