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

Изменение UIView при изменении ориентации

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

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

4b9b3361

Ответ 1

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

 #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];
}

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

Ответ 2

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

`

- (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 на основе ориентации. Единственным недостатком является то, что текущее фоновое изображение не отображается в построителе интерфейса, поскольку оно обрабатывается с помощью кода.

Ответ 3

Одно небольшое дополнение к подходу Madhup, что здорово. Я нашел, что мне нужно добавить это в 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

Ответ 4

Вы можете инкапсулировать это полностью в свой 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")
    }
  }
}