UIViewController shouldAutorotateToInterfaceOrientation - хотел бы добавить гистерезис - PullRequest
0 голосов
/ 03 октября 2011

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

самое близкое, что я могу получить к этому (что отнюдь не то, что я хочу, так как он блокирует пользовательский интерфейс):

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.

    [NSThread sleepForTimeInterval:2.0];
    return YES;
}

я хотел бы использовать что-то вроде этого - что в принципе работает, проверяя журнал консоли, но мне нужна соответствующая строка кода, которая была закомментирована.

-(void) deferredAutorotateToInterfaceOrientation:(NSTimer *) timer { 
    autoRotationTimer = nil;

    UIInterfaceOrientation interfaceOrientation = (UIInterfaceOrientation)[timer.userInfo integerValue];

    NSLog(@"switching to new orientation %d now",interfaceOrientation);

    // replace this with code to induce manual orientation switch here.
    //[self forceAutoRotateToInterfaceOrientation:interfaceOrientation];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    [autoRotationTimer invalidate];

    autoRotationTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self 
                                   selector:@selector(deferredAutorotateToInterfaceOrientation:) userInfo:[NSNumber numberWithInt:(int)interfaceOrientation ] repeats:NO];

    NSLog(@"denying autorotate, deffering switch to orientation %d by 2 seconds",interfaceOrientation);

    return NO;
}

Я понимаю, что иногда есть много способов сделать что-то, поэтому, если этот подход не самый эффективный, и кто-то может предложить другой способ сделать это, я весь в ушах. Мой главный критерий - я хочу отложить начало автоповорота, сохраняя при этом отзывчивый пользовательский интерфейс, если на самом деле они только слегка наклонились влево, потому что они в шине, которая только что свернула за угол и т. Д.

РЕДАКТИРОВАТЬ: Я нашел решение, которое не может быть дружественным к магазину приложений, однако я нахожусь в нескольких неделях от завершения, и кто-то может ответить на это тем временем. это работает вызывает недокументированный метод. Типовое преобразование (UIPrintInfoOrientation) просто для подавления предупреждения компилятора и не влияет на передаваемое значение.

-(void ) forceUIOrientationInterfaceOrientation:(UIDeviceOrientation) interfaceMode {
    [(id)[UIDevice currentDevice] setOrientation:(UIPrintInfoOrientation) interfaceMode];
}

Полная реализация, которая включает отрицание повторного входа, выглядит следующим образом:

- (void)viewDidLoad {
    [super viewDidLoad];
    acceptNewAutoRotation = YES;
}

-(void ) forceUIOrientationInterfaceOrientation:(UIDeviceOrientation) interfaceMode {
    [(id)[UIDevice currentDevice] setOrientation:(UIPrintInfoOrientation) interfaceMode];
}

-(void) deferredAutorotateToInterfaceOrientation:(NSTimer *) timer { 
    autoRotationTimer = nil;

    acceptNewAutoRotation = YES;

    [self forceUIOrientationInterfaceOrientation:[[UIDevice currentDevice] orientation]];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    [autoRotationTimer invalidate];

    if (acceptNewAutoRotation) {
        autoRotationTimer = nil;
         acceptNewAutoRotation = NO;
        return YES;
    } else {     

        autoRotationTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self 
                                                           selector:@selector(deferredAutorotateToInterfaceOrientation:) userInfo:[NSNumber numberWithInt:(int)interfaceOrientation ] repeats:NO];


        return  NO;
    }    

}

Ответы [ 2 ]

0 голосов
/ 03 октября 2011

Я не проверял это, и оно может вообще не работать, но вы можете попробовать это:

начать self.rotate = NO; затем:

- (void)shouldRotateTo:(UIInteraceOrientation *)interfaceOrientation {
    self.rotate = YES;
    // or test interfaceOrientation and assign accordingly.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    bool rot = self.rotate;
    self.rotate = NO
    [self performSelector:selector(shouldRotateTo:) withObject:[NSNumber numberWithInt:interfaceOrientation] afterDelay:2.0];
    return rot;
}

Параметр interfaceOrientation - это перечисление ( UIInteraceOrientation ), поэтому при передаче оберните его в NSNumber.

0 голосов
/ 03 октября 2011

Чтобы сделать это с общедоступными API, вам, вероятно, придется забыть об автоповороте и выполнить все собственные преобразования представления вручную на основе отфильтрованного (не просто с задержкой!) Ввода акселерометра.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...