Поверните UIViewController, чтобы противодействовать изменениям в UIInterfaceOrientation

StackOverflow https://stackoverflow.com/questions/2489845

Вопрос

Я много искал по этому поводу и не могу найти ничего, что могло бы мне помочь.

У меня есть UIViewController, содержащийся в другом UIViewController.Когда родительский UIViewController поворачивается, скажем, с портретного на LandscapeLeft , я хочу, чтобы это выглядело так, как будто дочерний элемент не вращался.То есть так сказать.Я хочу, чтобы дочерний элемент имел одинаковую ориентацию по отношению к небу независимо от ориентации родителя.Если у него есть UIButton, который находится вертикально в портретном режиме, я хочу, чтобы правая сторона кнопки была "вверх" в UIInterfaceOrientationLandscapeLeft .

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

-(void) rotate:(UIInterfaceOrientation)fromOrientation: toOr:(UIInterfaceOrientation)toOrientation
{
    if(((fromOrientation == UIInterfaceOrientationPortrait) && (toOrientation == UIInterfaceOrientationLandscapeRight))
       || ((fromOrientation == UIInterfaceOrientationPortraitUpsideDown) && (toOrientation == UIInterfaceOrientationLandscapeLeft)))
    {

    }
    if(((fromOrientation == UIInterfaceOrientationLandscapeRight) && (toOrientation == UIInterfaceOrientationPortraitUpsideDown))
       || ((fromOrientation == UIInterfaceOrientationLandscapeLeft) && (toOrientation == UIInterfaceOrientationPortrait)))
    {

    }
    if(((fromOrientation == UIInterfaceOrientationPortrait) && (toOrientation == UIInterfaceOrientationLandscapeLeft))
       || ((fromOrientation == UIInterfaceOrientationPortraitUpsideDown) && (toOrientation == UIInterfaceOrientationLandscapeRight)))
    {

    }
    if(((fromOrientation == UIInterfaceOrientationLandscapeLeft) && (toOrientation == UIInterfaceOrientationPortraitUpsideDown))
       || ((fromOrientation == UIInterfaceOrientationLandscapeRight) && (toOrientation == UIInterfaceOrientationPortrait)))
    {

    }
    if(((fromOrientation == UIInterfaceOrientationPortrait) && (toOrientation == UIInterfaceOrientationPortraitUpsideDown))
       || ((fromOrientation == UIInterfaceOrientationPortraitUpsideDown) && (toOrientation == UIInterfaceOrientationPortrait)))
    {

    }
    if(((fromOrientation == UIInterfaceOrientationLandscapeLeft) && (toOrientation == UIInterfaceOrientationLandscapeRight))
       || ((fromOrientation == UIInterfaceOrientationLandscapeRight) && (toOrientation == UIInterfaceOrientationLandscapeLeft)))
    {

    }   
}

что кажется совершенно бесполезной тратой кода.Кроме того, я планировал использовать CGAffineTransform (как указано здесь: http://www.crystalminds.nl/?p=1102) но я в замешательстве по поводу того, должен ли я изменять размеры вида, чтобы они соответствовали тому, какими они будут после поворота.

Большой кошмар здесь заключается в том, что вам приходится отслеживать глобальную переменную "orientation".Если вы этого не сделаете, иллюзия будет потеряна, и ViewController превратится во что угодно.

Мне действительно не помешала бы некоторая помощь в этом, спасибо!

Это было полезно?

Решение

Лучшее, что вы можете сделать, это изменить рамки фреймов подвида ur в соответствии с ориентацией интерфейса ur.Вы можете сделать это следующим образом:

 #pragma mark -
 #pragma mark InterfaceOrientationMethods

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown || interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
    if(toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown){
        //self.view = portraitView;
        [self changeTheViewToPortrait:YES andDuration:duration];

    }
    else if(toInterfaceOrientation == UIInterfaceOrientationLandscapeRight || toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft){
        //self.view = landscapeView;
        [self changeTheViewToPortrait:NO andDuration:duration];
    }
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------

- (void) changeTheViewToPortrait:(BOOL)portrait andDuration:(NSTimeInterval)duration{

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:duration];

    if(portrait){
        //change the view and subview frames for the portrait view
    }
    else{   
        //change the view and subview  frames for the landscape view
    }

    [UIView commitAnimations];
}

Надеюсь, это поможет.

Другие советы

я кое-что понял..допустим, наш проект имеет несколько уровней ViewController (как в случае, если вы добавляете подвиды другого контроллера представления к вашему контроллеру представления)

willRotateToInterfaceOrientation: метод продолжительности не будет вызываться для 2-го уровня ViewController...

итак, что я сделал, после того, как я инициализирую свой контроллер просмотра 2-го уровня с самого верхнего уровня, затем, когда метод willRotateToInterfaceOrientation: duration вызывается на самом верхнем уровне, я вызову willRotateToInterfaceOrientation: duration и для контроллера просмотра 2-го уровня

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top