текущая ориентация устройства iphone во ViewDidLoad - PullRequest
8 голосов
/ 19 марта 2012

Пожалуйста, помогите мне. У меня есть методы:

-(void) getCurrentOrientation{

    UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];

    if(orientation == UIInterfaceOrientationPortrait){
        NSLog(@"portrait");
    } else if(orientation == UIInterfaceOrientationLandscapeRight) {
        NSLog(@"LandscapeRight");
    } else if(orientation == UIInterfaceOrientationLandscapeLeft) {
        NSLog(@"LandscapeLeft");
    }   
}

но когда я вызываю это getCurrentOrientation, бросаем viewDidLoad

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self getCurrentOrientation];

}

NSLog пуст. В чем дело ? Я тоже попробую

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

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

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

    {
        NSLog(@"LandscapeRight"); 
    }

}

но этот вариант тоже пустой.

Мне нужно знать, в каком ОРИЕНТАЦИИ пользователь запускает приложение!

Пожалуйста, дайте мне любой совет.

Ответы [ 6 ]

15 голосов
/ 19 марта 2012

Ваш код абсолютно правильный и проблем нет.

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

Это утверждение работает только в оригинальных устройствах.

Однако вы хотите проверить в симуляторе, вы можете проверить как

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

Обновление:

Я проверил вас как на устройстве, так и на симуляторе. Изначально он будет показывать портрет только в viewDidLoad, хотя вы будете держать устройство в альбомной ориентации. Первый контроллер изучит метод shouldAutoRotate.

Вы не должны зависеть от viewDidLoad для начальной ориентации. Вы должны полагаться на метод shouldAutorotate изначально для точной ориентации.

4 голосов
/ 11 февраля 2017

При первой загрузке приложения 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
}
2 голосов
/ 19 марта 2012

Если вы хотите просто проверить ориентацию приложения, используйте следующий код:

- (void) viewDidLoad {
    [super viewDidLoad];
    BOOL isPortrait = UIDeviceOrientationIsPortrait(self.interfaceOrientation);
    // now do whatever you need
}

или

-(void)viewDidLoad
{
    if  (UIInterfaceOrientationIsLandscape(self.interfaceOrientation))
    {
        //landscape view code
    } 
    else
    {
         //portrait view code
    }
}
2 голосов
/ 19 марта 2012

Попробуйте заменить свой shouldAutorotateMethod следующим образом shouldAutorotate

  - (BOOL)shouldAutorotateToInterfaceOrientation (UIInterfaceOrientation)interfaceOrientation
  {
       if(interfaceOrientation == UIInterfaceOrientationPortrait){
          NSLog(@"portrait");    
       } else if(interfaceOrientation == UIInterfaceOrientationLandscapeRight) {       
          NSLog(@"LandscapeRight");        
       } else if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft) {      
          NSLog(@"LandscapeLeft"); 
       }   
       return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown)
  }

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

1 голос
/ 19 марта 2012

Твой viewDidLoad называется? Вы поставили точку останова там?

Как насчет печати NSLog(@"%i", [[UIDevice currentDevice] orientation])?

В документации сказано, что ориентация всегда возвращает 0, если вы не вызывали beginGeneratingDeviceOrientationNotifications. Возможно, вызвать его непосредственно перед попыткой ориентации недостаточно. Попробуйте перевести звонок на application:didFinishLaunchingWithOptions:.

Однако лучше всего использовать ориентацию, заданную контроллером - [UIViewController interfaceOrientation] и параметр, переданный shouldAutorotateToInterfaceOrientation.

0 голосов
/ 23 марта 2018

в быстром 3 или быстром 4.Вы можете использовать этот код в viewDidLoad () ..

`let orientation = UIApplication.shared.statusBarOrientation
 if orientation == .portrait {
        // portrait   
 } else if orientation == .landscapeRight || orientation == 
.landscapeLeft{
         // landscape     
 }`
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...