ViewDidLoad中的iphone设备当前方向

9 iphone ios

请帮我.我有方法:

-(void) getCurrentOrientation{

    UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];

    if(orientation == UIInterfaceOrientationPortrait){
        NSLog(@"portrait");
    } else if(orientation == UIInterfaceOrientationLandscapeRight) {
        NSLog(@"LandscapeRight");
    } else if(orientation == UIInterfaceOrientationLandscapeLeft) {
        NSLog(@"LandscapeLeft");
    }   
}
Run Code Online (Sandbox Code Playgroud)

但是当我调用这个getCurrentOrientation时抛出viewDidLoad

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self getCurrentOrientation];

}
Run Code Online (Sandbox Code Playgroud)

NSLog是空的.怎么了 ?我也试试

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

    if ( ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait)) {
        NSLog(@"portrait");

    } else if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight) 

    {
        NSLog(@"LandscapeRight"); 
    }

}
Run Code Online (Sandbox Code Playgroud)

但那个varint也是空的.

我需要知道哪个ORIENTATION用户启动APP!

拜托,给我任何建议.

Jan*_*mal 15

您的代码绝对正确,没有问题.

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
Run Code Online (Sandbox Code Playgroud)

此声明仅适用于原始设备.

但是,您想要检查模拟器,您可以检查

UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
    // portrait             
} else {
    // landscape
}
Run Code Online (Sandbox Code Playgroud)

更新:

我已经在设备和模拟器中测试了你.最初它只会在viewDidLoad中显示肖像,但您会将设备保持在横向状态.First Controller将研究shouldAutoRotate方法.

您不应该依赖viewDidLoad初始方向.您最初应该依赖于shouldAutorotate方法来确切定位.


Har*_*ris 6

首次加载应用程序时,UIDevice.current.orientation无效。但是UIApplication.shared.statusBarOrientation是。通常,UIDevice.current.orientation是检查方向的更好方法。因此,此方法将处理所有情况

var isLandscape: Bool {
    return UIDevice.current.orientation.isValidInterfaceOrientation 
        ? UIDevice.current.orientation.isLandscape 
        : UIApplication.shared.statusBarOrientation.isLandscape
}
Run Code Online (Sandbox Code Playgroud)