如何在以下应用程序状态中查找设备方向:
- 首次启动应用程序
- 应用进入前台
您可以在第一次启动应用程序时检测方向,如下所示:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(deviceOrientationDidChange:) name: UIDeviceOrientationDidChangeNotification object: nil];
}
要检测方向:
-(void)deviceOrientationDidChange:(NSNotification *)notification
{
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
//Ignoring specific orientations
if (orientation == UIDeviceOrientationFaceUp || orientation == UIDeviceOrientationFaceDown || orientation == UIDeviceOrientationUnknown || currentOrientation == orientation)
{
//To check orientation ;
}
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"deveiceorientation"])
{
// your orientation
}
else
{
[[NSUserDefaults standardUserDefaults] setObject:deviceOrientaion forKey:@"deveiceorientation"];
[[NSUserDefaults standardUserDefaults] synchronize];
// save your orientation
}
}
在应用程序进入前台时,您可以使用
-(void)viewDidAppear:(BOOL)animated{
}
如果您尝试打开设备方向通知,则可以收到有关设备方向更改的通知,但我不确定您是否可以通过这种方式可靠地找到启动时的当前方向。
如果您在需要设备方向时碰巧在视图控制器代码中,那么最好在需要方向时直接询问视图控制器,例如:
self.interfaceOrientation
whenself
是 UIViewController 的一个实例。通常重要的是要知道您是处于纵向还是横向模式,在这种情况下,您将拥有以下内容:
const UIInterfaceOrientation currentInterfaceOrientation = self.interfaceOrientation;
if (UIInterfaceOrientationIsLandscape(currentInterfaceOrientation)) {
// Set up for landscape orientation.
} else {
// Set up for portrait orientation (including upside-down orientation).
}
编辑: 您需要在方法之外对设备方向进行初始检查application:didFinishLaunching:withOptions:
。您可以使用dispatch_after
延迟执行设备方向的初始检查。我不确定我是否喜欢你在这里使用的模式,但我认为这对你有用,在你的application:didFinishLaunchingWithOptions:
方法结束时:
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
__block UIDeviceOrientation initialDeviceOrientation;
double delayInSeconds = 0.1;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
initialDeviceOrientation = [[UIDevice currentDevice] orientation];
NSLog(@"initialDeviceOrientation = %u", initialDeviceOrientation);
});
// Etc.