如何在iOS 6中以编程方式获取设备的当前方向?

Cod*_*ter 20 iphone screen-orientation device-orientation ipad-3 ios6

我开发了iOS应用程序并在iOS6设备上进行了测试.在测试时,我意识到我的应用程序没有按预期响应方向更改.

这是我的代码:

// Autorotation (iOS >= 6.0)
- (BOOL) shouldAutorotate
{
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationMaskPortrait;
}
Run Code Online (Sandbox Code Playgroud)

确切地说,我想知道iOS中的方向更改调用了哪些方法.

She*_*pta 55

你可以尝试这个,可以帮助你:

如何在iOS 6中以编程方式更改设备方向

要么

Objective-C的:

UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]
Run Code Online (Sandbox Code Playgroud)

迅速:

if UIDevice.current.orientation.isLandscape {
    // Landscape mode
} else {
    // Portrait mode
}
Run Code Online (Sandbox Code Playgroud)

  • 注意`| | orientation |的值 除非通过调用beginGeneratingDeviceOrientationNotifications启用了方向通知,否则属性始终返回0. [文档](http://developer.apple.com/library/ios/documentation/uikit/reference/UIDevice_Class/Reference/UIDevice.html#//apple_ref/DOC/UID/TP40006902-CH3-SW3) (11认同)

Gir*_*ish 36

你可以尝试这个,这解决了你的问题.

UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
Run Code Online (Sandbox Code Playgroud)

请参阅以下链接App extension 获取设备当前方向(应用程序扩展)

  • 真不好主意.不要挂在那个属性上. (2认同)
  • 有人可以设置这个属性[`statusBarOrientation`](http://developer.apple.com/library/ios/DOCUMENTATION/UIKit/Reference/UIApplication_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006728- CH3-SW10)它将不再与真正的`interfaceOrientation`相同.`如果设备改变方向,则此方法设置的状态栏方向不会改变 (2认同)
  • @DanSkeel怎么可能.我们使用此属性获取确切的当前方向.如果我们强制设置状态栏方向,那么我们有责任小心处理它. (2认同)
  • 我的意思是你无法控制使用你的框架的整个应用程序的代码.因为你正在编写框架,而不是应用程序.开发人员可以设置,你不会知道它. (2认同)

Lau*_*Lau 6

也许是愚蠢但它有效(仅在ViewController中):

if (self.view.frame.size.width > self.view.frame.size.height) {
    NSLog(@"Hello Landscape");
}
Run Code Online (Sandbox Code Playgroud)


Vic*_*cky 5

  @property (nonatomic) UIDeviceOrientation m_CurrentOrientation ;
Run Code Online (Sandbox Code Playgroud)

/*您需要在ViewDidload或ViewWillAppear*/中声明这些代码

- (void)viewDidLoad

   {

   [super viewDidLoad];

   [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

   [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(deviceOrientationDidChange:) name: UIDeviceOrientationDidChangeNotification object: nil];
}
Run Code Online (Sandbox Code Playgroud)

/*现在我们的设备会在我们更改设备方向时发出通知,因此您可以使用当前方向控制代码或程序*/

- (void)deviceOrientationDidChange:(NSNotification *)notification

 {

 //Obtaining the current device orientation

 /* Where self.m_CurrentOrientation is member variable in my class of type UIDeviceOrientation */

 self.m_CurrentOrientation = [[UIDevice currentDevice] orientation];

    // Do your Code using the current Orienation 

 }
Run Code Online (Sandbox Code Playgroud)