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

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

У меня есть UIViewController, содержащийся в другом UIViewController. Когда родительский UIViewController вращается, скажем, из Portrait в LandscapeLeft, я хочу, чтобы это выглядело так, как будто ребенок не вращался. Так сказать. Я хочу, чтобы ребенок имел одинаковую ориентацию на небо независимо от ориентации родителей. Если он имеет UIButton, который находится в вертикальном положении в Portrait, я хочу, чтобы правая сторона кнопки была "вверху" в 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), но я не уверен, стоит ли менять размеры представления так, чтобы они были такими, какими они будут после поворота,

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

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

2 ответа

Решение

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

 #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-го уровня

Другие вопросы по тегам