2010-04-29 7 views
12

Эй, все. У меня довольно простой вопрос. Я разрабатываю «богатое» приложение для iPad, и у меня есть два фоновых изображения, специально предназначенных для пейзажа и портрета. Я бы хотел, чтобы этот ImageView автоматически менялся в зависимости от ориентации устройств. (например, почти все приложения Apple iPad).Изменение UIView при изменении ориентации

Может ли кто-нибудь указать мне правильное направление? Я предполагаю, что это будет что-то, что я делаю на viewDidLoad ..

+0

Возможное повторение http://stackoverflow.com/questions/2489845/rotate-uiviewcontroller-to-counteract-changes-in-uiinterfaceorientation/2490719#2490719 –

ответ

22

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

#pragma mark - 
#pragma mark InterfaceOrientationMethods 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { 
    return (UIInterfaceOrientationIsPortrait(interfaceOrientation) || UIInterfaceOrientationIsLandscape(interfaceOrientation)); 
} 

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

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

    } 
    else if(UIInterfaceOrientationIsLandscape(toInterfaceOrientation)){ 
     //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]; 
} 

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

+0

Это сделал трюк, спасибо! – Designeveloper

+0

Макросы 'UIInterfaceOrientationIsPortrait()' и 'UIInterfaceOrientationIsLandscape()' действительно увеличивают читаемость для этих типов ситуаций ... но, отличное решение, тем не менее! – Nate

+0

@Nate Спасибо за предложение .. Изменен ответ. :) –

9

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

`

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation) interfaceOrientation duration:(NSTimeInterval)duration { 
    if (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == 
     UIInterfaceOrientationPortraitUpsideDown) { 
     [brownBackground setImage:[UIImage imageNamed:@"Portrait_Background.png"]]; 
    } else { 
     [brownBackground setImage:[UIImage imageNamed:@"Landscape_Background.png"]]; 
    } 
} 

`

Изменение фона объявленного UIImageView, основанный на ориентации. Единственным недостатком является то, что текущее фоновое изображение не отображается в построителе интерфейса, поскольку оно обрабатывается кодом.

7

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

// set background image 
if (self.interfaceOrientation == UIInterfaceOrientationPortrait || self.interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) { 
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"portraitBG.png"]]; 
} else { 
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"landscapeBG.png"]]; 
} 

Еще раз спасибо Madhup

+0

это самый правильный способ –

+0

+1 для 'self.interfaceOrientation' –

0

Вы можете инкапсулировать это полностью в вашем UIView, наблюдая ли bounds.width > bounds.height

Этот может быть желательно, если вы пишете небольшой, самоконтроль.

class MyView: UIView { 
    override func layoutSubviews() { 
    super.layoutSubviews() 
    if bounds.height > bounds.width { 
     println("PORTRAIT. some bounds-impacting event happened") 
    } else { 
     println("LANDSCAPE") 
    } 
    } 
} 
Смежные вопросы