Iphone 如何正确地知道设备的方向

Iphone 如何正确地知道设备的方向,iphone,ipad,device-orientation,Iphone,Ipad,Device Orientation,我想知道用户启动我的应用程序时设备的方向,以便生成不同的视图。我觉得奇怪的是: - (void)viewDidLoad { if ([UIDevice currentDevice].orientation == UIDeviceOrientationPortrait) { NSLog(@"1"); } if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight)

我想知道用户启动我的应用程序时设备的方向,以便生成不同的视图。我觉得奇怪的是:

- (void)viewDidLoad
{
    if ([UIDevice currentDevice].orientation == UIDeviceOrientationPortrait) {
        NSLog(@"1");
    }
    if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight) {
        NSLog(@"2");
    }
    if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft) {
        NSLog(@"3");
    }
    if ([UIDevice currentDevice].orientation == UIDeviceOrientationPortraitUpsideDown) {
        NSLog(@"4");
    }
}

没有人被打印出来!我是在ipad模拟器上做的,我认为方向应该是UIDeviceOrientationGrait。为什么会这样?以及如何正确地知道方向?

可能是模拟器根本无法处于方向状态(没有意义,因为您无法真正旋转计算机…)您是否检查了它是否返回
UIDeviceOrientationUnknown

尝试使用

[UIApplication sharedApplication].statusBarOrientation
而不是

[UIDevice currentDevice].orientation

文件或设备说明:

使用“方向”属性或获取当前方向 通过注册来接收更改通知 UIDeviceOrientationIDChangeNotification通知。使用前 要获取方向数据,必须启用以下任一技术 使用BegingeratingDeviceOrientationNotifications进行数据传递 方法

因此,可能是因为您从未开始生成方向通知,所以您得到了未知的方向

您还应该在viewDidLoad中记录该值,以确认在获得方向时收到的确切信息。这将是进一步调查的良好起点

Use this :-

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {      
if(interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)     
{       
 //code for portrait   

 }            
else      
{         //code for Landscape 

  }     
return (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationPortrait ||interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown); 
} 
  • (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation是uiviewcontroller的委托方法
根据,除非首先调用了
-BegingeratingDeviceOrientationNotifications
,否则
UIDevice
orientation
属性将始终返回0(即
UIDeviceOrientationUnknown
)。此方法将启用加速计,发送通知更改,并更新
ui设备的
orientation
属性