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

Ориентация UIDevice

У меня есть следующий код в методе. Когда я запускаю это в симуляторе, отладчик проскакивает прямо над кодом? Что мне не хватает?

if (([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) || 
        ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)) 
{       

} else {

}
4b9b3361

Ответ 1

Обновление 2

Это не имеет значения, но попробуйте включить уведомления о направлениях:

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];


[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(detectOrientation) name:@"UIDeviceOrientationDidChangeNotification" object:nil];

Update

Плохо, я предположил, что он пуст.

Попробуйте удалить оператор или просто проверить для одной ориентации. Посмотрите, исправляет ли это это. Возможно, есть проблема с скобками или что-то глупое.

У меня есть следующий тест, работающий в производственном коде, поэтому ваш метод должен работать:

    if (([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) || 
        ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)) {


}

Оригинальный ответ

Вы должны на самом деле поместить утверждения в блоки if, чтобы заставить его войти.

Отладчик достаточно умен, чтобы пропускать пустые блоки.

Ответ 2

Лучшим способом определения ориентации интерфейса является просмотр ориентации строки состояния:

 UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];

    if(orientation == UIInterfaceOrientationPortrait || 
       orientation == UIInterfaceOrientationPortraitUpsideDown) {

       //Portrait orientation

}

if(orientation == UIInterfaceOrientationLandscapeRight ||
   orientation == UIInterfaceOrientationLandscapeLeft) {

    //Landscape orientation

}

UIDevice класс измеряет ориентацию на основе акселерометра, и если устройство лежит ровно, оно не вернет правильную ориентацию.

Ответ 3

Обратите внимание, что есть макрос UIDeviceOrientationIsLandscape и UIDeviceOrientationIsPortrait, поэтому вместо того, чтобы сравнивать его отдельно с LandscapeLeft и LandscapeRight, вы можете просто сделать это следующим образом:

if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation))
{
}

Ответ 4

Другой способ сделать это без включения уведомления о ориентации будет

Шаг 1: Сохраните текущую ориентацию в локальной переменной myCurrentOrientation и назначьте ее следующим образом:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
                                duration:(NSTimeInterval)duration
{
    myCurrentOrientation = toInterfaceOrientation;
}

Шаг 2: Используйте myCurrentOrientation для вашей проверки

if (UIInterfaceOrientationIsLandscape(myCurrentOrientation) == YES) {
    // landscape
}
else {
    // portrait.
}

Ответ 5

Привет, вам нужно позвонить [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications] перед получением значения. Посмотрите документацию по этому методу. Потребовал мне время, чтобы отследить это.

Ответ 6

Скажите, что вы находитесь в настройке Springboard и хотите показать что-то в зависимости от ориентации текущего приложения, тогда вы можете использовать это (только для джейлбрейка):

UIInterfaceOrientation o = [[UIApplication sharedApplication] _frontMostAppOrientation];

Ответ 7

Я рекомендую вам использовать мой выделенный код вместо вашего, чтобы защитить некоторый код строк.

-(void) viewDidLoad
{
    [super viewDidLoad];
    [self rotations];
}

-(void)rotations
{
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(orientationChanged:)
                                         name:UIDeviceOrientationDidChangeNotification
                                         object:nil];
}

-(void) orientationChanged:(NSNotification *)notification
{
    //USE THIS PART
    //USE THIS PART
    //USE THIS PART
    //USE THIS PART
    //USE THIS PART
    if (UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation))
    {
    }
}

ВМЕСТО

if([[UIDevice currentDevice] orientation] == UIInterfaceOrientationPortrait || 
   [[UIDevice currentDevice] orientation] == UIInterfaceOrientationPortraitUpsideDown) 
{
}

Ответ 8

Вот способ поиска ориентации и истинного центра экрана. Я использовал метод Tuszy, чтобы я мог правильно настроить UIActivityIndicatorView.

- (BOOL) isPortraitOrientation {
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    if(orientation == UIInterfaceOrientationPortrait ||
       orientation == UIInterfaceOrientationPortraitUpsideDown) {
        return true;
    }
    if(orientation == UIInterfaceOrientationLandscapeRight ||
       orientation == UIInterfaceOrientationLandscapeLeft) {
        return false;
    }
    return false;
}

И способ получить центр...

- (void) findMyUIViewCenter {
    CGPoint myCenter;
    if ([self isPortraitOrientation]) {
        myCenter = self.view.center;
    }
    else {
        myCenter = CGPointMake(self.view.frame.size.height / 2.0, self.view.frame.size.width / 2.0);
    }
    NSLog(@"true center -- x:%f y:%f )",myCenter.x,myCenter.y);
}