Подтвердить что ты не робот

Как проверить, в каком месте (пейзаж или портрет) сейчас находится iPhone?

У меня есть приложение с панелью вкладок и контроллерами навигации на каждой вкладке. Когда пользователь встряхивает устройство, в навигационном контроллере отображается дочерний вид UIImageView. Но UIImageView должен содержать специальное изображение, в зависимости от текущей ориентации устройства.

Если я пишу только

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)
   if (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) { 
   //Code
   }
   else if (interfaceOrientation == UIInterfaceOrientationLandscapeRight||interfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
   //Code
   }
}

Взгляд просто сумасшедший, если пользователь повернул устройство перед тем, как встряхнуть.

Есть ли способ получить текущую ориентацию iPhone?

4b9b3361

Ответ 1

Используйте метод [[UIDevice currentDevice] orientation], как указано здесь.

Ответ 2

Вот макросы UIDeviceOrientationIsLandscape и UIDeviceOrientationIsPortrait

поэтому достаточно проверить отдельно, вы можете сделать это вот так...

if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation))
{
    // code for landscape orientation      
}

ИЛИ

 if (UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation))
 {
     // code for Portrait orientation       
 }

Ответ 3

Как сказал Бено, это кажется лучшим ответом, если вы обнаруживаете ориентацию на ранней стадии своего представления. Я не мог получить одобренный ответ, чтобы вернуть результат в начале моей установки, но это работает чудесно.

if (UIDeviceOrientationIsPortrait(self.interfaceOrientation)){
//DO Portrait
}else{
//DO Landscape
}

Ответ 4

Чтобы добавить к уже ответившему вопросу:

Вы используете [[UIDevice currentDevice] orientation], который даст одно из следующих значений:

typedef enum {
   UIDeviceOrientationUnknown,
   UIDeviceOrientationPortrait,
   UIDeviceOrientationPortraitUpsideDown,
   UIDeviceOrientationLandscapeLeft,
   UIDeviceOrientationLandscapeRight,
   UIDeviceOrientationFaceUp,
   UIDeviceOrientationFaceDown
} UIDeviceOrientation;

Документацию можно найти здесь - (ориентация) и здесь - (UIDeviceOrientation).

(Я не хочу требовать прежнего андерсера, но эта информация была большой для комментария.)

Ответ 5

Попробуйте это:

[[UIApplication sharedApplication] statusBarOrientation]

Или в Swift 3:

UIApplication.shared.statusBarOrientation

Чтобы проверить конкретную ориентацию, вы также можете использовать свойство isLandscape или isPortrait следующим образом:

UIApplication.shared.statusBarOrientation.isLandscape

Проблема с [[UIDevice currentDevice] orientation] заключается в том, что он также возвращает UIInterfaceOrientationUnknown, а statusBarOrientation - нет.

Существует также свойство UIViewController interfaceOrientation, но оно устарело в iOS 8, поэтому не рекомендуется.

Вы проверяете документацию для statusBarOrientation здесь

Ответ 6

Вы также можете использовать свойство interfaceOrientation класса UIViewController, если вы застряли и постоянно получаете UIDeviceOrientationUnknown из UIDevice.

Там хорошо видно, почему [[UIDevice currentdevice] ориентация] может иногда терпеть неудачу: http://bynomial.com/blog/?p=25, особенно если вы хотите обнаружить (например, если вы хотите проверить, когда приложение выходит из фона).

Ответ 7

Это поможет вам...

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft || [[UIDevice currentDevice] orientation ]== UIDeviceOrientationLandscapeRight)
 {
   NSLog(@"Lanscapse");
 }
if([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait || [[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown )
 {
   NSLog(@"UIDeviceOrientationPortrait");
 }
}

Ответ 8

Вы также можете определить константы, чтобы заработать время:

#define LANDSCAPE UIInterfaceOrientationIsLandscape(self.interfaceOrientation)
#define LANDSCAPE_RIGHT [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft
#define LANDSCAPE_LEFT [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight
#define PORTRAIT UIInterfaceOrientationIsPortrait(self.interfaceOrientation)
#define PORTRAIT_REVERSE [UIDevice currentDevice].orientation == UIDeviceOrientationPortraitUpsideDown

Ответ 9

  • Как простое решение Swift 4.2

    override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
            switch UIDevice.current.orientation{
            case .portrait:
                print("Portrait")
            case .portraitUpsideDown:
                print("PortraitUpsideDown")
            case .landscapeLeft:
                print("LandscapeLeft")
            case .landscapeRight:
                print("LandscapeRight")
            default:
                print("Another")
            }
        }
    

Ответ 10

Вы можете проверить это так (Swift 3):

var isPortrait: Bool {
  let orientation = UIDevice.current.orientation
  switch orientation {
    case .portrait, .portraitUpsideDown:
      return true

    case .faceUp, .faceDown:
      // Check the interface orientation
      let interfaceOrientation = UIApplication.shared.statusBarOrientation
      switch interfaceOrientation{
        case .portrait, .portraitUpsideDown:
          return true
        default:
          return false
      }
   default: // .unknown
     return false // not very satisfying to return false as if we were in landscape :-/
   }
}

Если вы находитесь в ViewController, вы также можете сделать это так (именно это я и сделал):

private var isPortrait: Bool {
    let orientation = UIDevice.current.orientation
    switch orientation {
    case .portrait, .portraitUpsideDown:
        return true
    case .landscapeLeft, .landscapeRight:
        return false
    default: // unknown or faceUp or FaceDown
        return self.view.width < self.view.height
    }
}

Хотя даже этого должно быть достаточно в этом случае:

private var isPortrait: Bool {
     return self.view.width < self.view.height
}

Ответ 11

Обновив его до iOS 8+, где UIViewController.interfaceOrienation устарела, вы должны использовать traitCollections. Так, например, чтобы проверить ландшафт на iPhone, вы должны использовать:

if self.traitCollection.verticalSizeClass == .compact
{
  your code
}

Обратите внимание, что на iPad это не так, потому что на iPad в альбомной ориентации класс размера не compact. Ссылка на Apple Doc

Sizes from Apple

Ответ 12

Получение текущей ориентации

- (void)viewDidLoad
{
    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];

    if (orientation == UIInterfaceOrientationLandscapeLeft) {
        NSLog(@"Landscape left");
        self.lblInfo.text = @"Landscape left";
    } else if (orientation == UIInterfaceOrientationLandscapeRight) {
        NSLog(@"Landscape right");
        self.lblInfo.text = @"Landscape right";
    } else if (orientation == UIInterfaceOrientationPortrait) {
        NSLog(@"Portrait");
        self.lblInfo.text = @"Portrait";
    } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
        NSLog(@"Upside down");
        self.lblInfo.text = @"Upside down";
    }
}

Ответ 13

И если вы просто хотите, чтобы устройство было в горизонтальной или вертикальной ориентации, простое решение (в Swift):

var orientation = "portrait"
if UIScreen.main.bounds.size.width > UIScreen.main.bounds.size.height {
   orientation = "landscape"
}