Различные макеты в портретном и ландшафтном режимах

Предположим, у меня такой дизайн макета на iPad Portrait.

Screen1

Но я бы хотел, чтобы это было так, когда iPad в ландшафте: screen2

Можно ли сделать это с помощью автоматического макета? Или с небольшим количеством кода?

Ответы

Ответ 2

Вы можете достичь этого с помощью кода. Прежде всего, вы должны сделать IBoutlet своих динамических ограничений

Константное ограничение://это ограничение останется таким же в обеих ориентациях

1- RedView top Пространство для наблюдения

2 RedView Trailing Space to Superview

3- Пространство BlueView для наблюдения

4 BlueView bottom Пространство для SuperView

Динамическое ограничение

Контрастность портрета:

1- Высота RedView

2- Вертикальное пространство RedView для BlueView

3- RedView Ведущее пространство для наблюдения

4- Синее представление для наблюдения за просмотром

Ограничение LandScape:

1- Ширина RedView

2- Горизонтальное пространство RedView для BlueView

3 RedView bottom Пространство для наблюдения

4- BlueView Top Space to Superview

Теперь вам нужно переопределить метод, который вызывается при изменении ориентации

override func viewWillTransitionToSize(size: CGSize,   withTransitionCoordinator coordinator:    UIViewControllerTransitionCoordinator) {

    coordinator.animateAlongsideTransition({ (UIViewControllerTransitionCoordinatorContext) -> Void in

        let orient = UIApplication.sharedApplication().statusBarOrientation

        switch orient {
        case .Portrait:
            print("Portrait")
            self.ApplyportraitConstraint()
            break
            // Do something
        default:
            print("LandScape")
            // Do something else
            self.applyLandScapeConstraint()
            break
        }
        }, completion: { (UIViewControllerTransitionCoordinatorContext) -> Void in
            print("rotation completed")
    })
    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
}

И вызовите эти 2 функции

Портретная ориентация

func ApplyportraitConstraint(){

 self.view.addConstraint(self.RedViewHeight)
 self.view.addConstraint(self.RedView_VerticalSpace_To_BlueView)
 self.view.addConstraint(self.RedView_LeadingSpace_To_SuperView)
 self.view.addConstraint(self.BlueView_TrailingSpace_To_SuperView)

 self.view.removeConstraint(self.RedViewWidth)
 self.view.removeConstraint(self.RedView_HorizontalSpace_To_BlueView)
 self.view.removeConstraint(self.RedView_BottomSpace_To_SuperView)          
 self.view.removeConstraint(self.BlueView_TopSpace_To_SuperView)


}

Функция ориентации LandScape

    func applyLandScapeConstraint(){

    self.view.removeConstraint(self.RedViewHeight)
    self.view.removeConstraint(self.RedView_VerticalSpace_To_BlueView)
    self.view.removeConstraint(self.RedView_LeadingSpace_To_SuperView)
   self.view.removeConstraint(self.BlueView_TrailingSpace_To_SuperView)

    self.view.addConstraint(self.RedViewWidth)
    self.view.addConstraint(self.RedView_HorizontalSpace_To_BlueView)
    self.view.addConstraint(self.RedView_BottomSpace_To_SuperView)
    self.view.addConstraint(self.BlueView_TopSpace_To_SuperView)

}

Портрет ScreenShot: введите описание изображения здесь LandScape ScreenShot: введите описание изображения здесь

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

Github:

Если у вас есть предупреждения, просто установите приоритет ограничения высоты и ширины на 999.

Ответ 3

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

Для пользователей iPhone может быть полезно следующее.

Да, это возможно в конструкторе интерфейса с классами автозапуска и размера. Вам не нужно будет указывать код.

Сначала вы выбираете класс размера wAny hAny

Здесь описано, как выбрать класс размера.

введите описание изображения здесь

Добавьте два вида в свой контроллер. Красный вид сверху и синий вид ниже. Также как и ваше первое изображение.

Ограничения на красном просмотре:

  • Верхнее пространство для супер-просмотра
  • Ведущее пространство для супер-просмотра
  • Трейлинг пространства для супер просмотра
  • height = 50

Ограничения на синем изображении:

  • вертикальное пространство для красного представления
  • ведущее пространство для супер просмотра
  • трейлинг-пространство для супер-просмотра
  • нижнее пространство для супер просмотра

Все это настроено для режима Potrait.

Теперь вы меняете классы размера на wAny hCompact (первые два столбца в первой строке). этот класс предназначен для iPhone.

Теперь вы должны использовать установить и удалить.

Ограничения, которые будут меняться для красного просмотра:

  • Удалите его высоту constriant для класса (wAny hCompact) как:

введите описание изображения здесь

  • Similary удалите его ведущее ограничение. Добавьте к этому красному представлению в этом классе два новых ограничения:
  • Нижнее пространство для просмотра
  • Ограничение ширины = 50

Это сделает красный вид правой стороны шириной 50.

Теперь изменение ограничения для синего представления:

  • Удалите его вертикальное расстояние, конечное пространство.

Добавьте два новых ограничения:

  • Вертикальное пространство для супер-просмотра
  • Трейлинг пространства для красного просмотра

При этом будет красным изображение слева от синего.

Надеюсь, он сработает для вас.

Ответ 4

Можно ли сделать это с помощью автоматического макета? Или с небольшим количеством кода?

Вам понадобится сделать эти макеты для iPad.

  • Определите ограничения макета для каждого представления, не устанавливайте ограничения ширины и высоты для этих представлений.
  • Подключить IBOutlets для каждого ограничения для одного и двух видов.
  • Внесите протокол UIContentContainer в свой контроллер просмотра.

    viewWillTransitionToSize(_ size: CGSize,withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)

Обсуждение UIKit вызывает этот метод, прежде чем изменять размер представленный просмотр контроллеров представлений. Вы можете переопределить этот метод в своем собственные объекты и использовать его для выполнения дополнительных задач, связанных с размером изменение. Например, контроллер контейнера может использовать этот метод для переопределения черт встроенных контроллеров дочерних представлений. Использовать предоставил объект-координатор для анимации любых сделанных вами изменений.

Если вы переопределите этот метод в своих настраиваемых контроллерах представлений, всегда вызовите super в какой-то момент вашей реализации, чтобы UIKit мог переместите соответствующее сообщение об изменении размера. Просмотр контроллеров переслать сообщение об изменении размера в их представления и дочернее представление контроллеры. Контроллеры презентаций перенаправляют изменение размера на свои представленный контроллер представления.

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

  1. Отрегулируйте свои ограничения на основе того, будет ли устройство поворачиваться на портретный или альбомный.

Ответ 5

Я реализовал это с Obj-C и опубликовал на мой github Решение включает в себя небольшое количество кода, и большая часть работы сосредоточена на соглашениях AutoLayout и именования... Файл README объясняет, как я это сделал. Код, который я использовал в ViewController, в основном этот метод:

- (void)setUpViewConstraintsForInterfaceOrientation:(InterfaceOrientation)interfaceOrientation {
    self.lastOrientation = interfaceOrientation;
    if (interfaceOrientation == Landscape) {
        [NSLayoutConstraint deactivateConstraints:self.portraitConstraintsCollection];
        [NSLayoutConstraint activateConstraints:self.landscapeConstraintsCollection];
    } else if(interfaceOrientation == Portrait){
        [NSLayoutConstraint deactivateConstraints:self.landscapeConstraintsCollection];
        [NSLayoutConstraint activateConstraints:self.portraitConstraintsCollection];
    }
    [self.view layoutIfNeeded];
}

portraitConstraintsCollection and landscapeConstraintsCollection - это свойства IBOutletCollection для управления специфическими ограничениями ориентации.

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

Ответ 6

гораздо проще разместить эти два представления в представлении стека и изменить ориентацию оси для представления стека.

  • создать ссылку IBOulet на стеке
  • реализовать viewWillTransitionToSize
  • измените ось для каждой ориентации, выполнив self.stackView.axis =.vertical или. Horizontal

Ответ 7

Моя задача была похожа в общем. Мне нужны были портретные и ландшафтные ограничения для iPhone и iPad. Кроме того, расположение желтого и серого видов должно быть в целом одинаковым, но ширина желтого вида должна быть разной в iPhone и iPad (40% экрана в iPhone и 60% экрана в iPad): enter image description here

Ограничения для ориентации iPhone Я установил, используя наборы признаков и определяя для каждого ограничения, для какой коллекции он должен быть установлен. Для iPhone есть wChR (портрет) и wChC (пейзаж). Или wC с hAny:

enter image description here

Но для альбомной и портретной ориентации на iPad используются отдельные коллекции черт (wRhR), поэтому способ, используемый для iPhone, не подходит. Чтобы изменить ограничения для этих случаев, я делаю два набора ограничений (первый для iPad в альбомной ориентации и второй для iPad в портретной):

@property (strong, nonatomic) IBOutletCollection(NSLayoutConstraint) NSArray *ipadLandscapeConstraints;
@property (strong, nonatomic) IBOutletCollection(NSLayoutConstraint) NSArray *ipadPortraitConstraints;

Примечание: 1. Для этого выберите несколько необходимых ограничений в раскадровке и подключите их к вашему файлу .m. Чтобы увидеть, какие ограничения были добавлены в массив, нажмите кнопку ‘+ слева от него для свойства в файле .m: enter image description here 2. Я использовал приоритет ограничения для разрешения конфликтов ограничений для iPad

Наконец, я реализовал метод configConstraints для переключения наборов ограничений в соответствии с ориентацией iPad и переопределил метод viewWillTransitionToSize:

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    [self configConstraints];
}

- (void)configConstraints {
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        // iPad landscape orientation
        if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)) {
            [NSLayoutConstraint deactivateConstraints:self.ipadPortraitConstraints];
            [NSLayoutConstraint activateConstraints:self.ipadLandscapeConstraints];
        }
        // iPad portrait orientation
        else {
            [NSLayoutConstraint deactivateConstraints:self.ipadLandscapeConstraints];
            [NSLayoutConstraint activateConstraints:self.ipadPortraitConstraints];
        }
        [self.view layoutIfNeeded];
    }
}

Возможно, потребуется вызвать метод configConstraints в других местах, где представление загружается или появляется, но основная идея описана выше.

Ответ 8

Единственный способ, которым я легко достиг этого, так что он работает на iPad и iPhone, - это сделать это программно. Это делается с помощью Swift 5.0 в Xcode 10.2.

В вашем ViewController определите два вида, которые вы хотите изменить в зависимости от ориентации:

@IBOutlet weak var raceInfoView: UIStackView!
@IBOutlet weak var raceListView: UITableView!

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

private var portraitRaceInfoViewTrailing: NSLayoutConstraint!
private var portraitRaceInfoViewBottom: NSLayoutConstraint!
private var portraitRaceListViewLeading: NSLayoutConstraint!
private var landscapeRaceInfoViewTrailing: NSLayoutConstraint!
private var landscapeRaceInfoViewBottom: NSLayoutConstraint!
private var landscapeRaceListViewTop: NSLayoutConstraint!

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

override func viewDidLoad() {
    super.viewDidLoad()

    portraitRaceInfoViewTrailing = NSLayoutConstraint(
        item: racesView as Any, attribute: NSLayoutConstraint.Attribute.trailing,
        relatedBy: NSLayoutConstraint.Relation.equal,
        toItem: raceInfoView, attribute: NSLayoutConstraint.Attribute.trailing,
        multiplier: 1, constant: 0)
    portraitRaceInfoViewBottom = NSLayoutConstraint(
        item: raceListView as Any, attribute: NSLayoutConstraint.Attribute.top,
        relatedBy: NSLayoutConstraint.Relation.equal,
        toItem: raceInfoView, attribute: NSLayoutConstraint.Attribute.bottom,
        multiplier: 1, constant: 0)
    portraitRaceListViewLeading = NSLayoutConstraint(
        item: raceListView as Any, attribute: NSLayoutConstraint.Attribute.leading,
        relatedBy: NSLayoutConstraint.Relation.equal,
        toItem: racesView, attribute: NSLayoutConstraint.Attribute.leading,
        multiplier: 1, constant: 0)

    landscapeRaceInfoViewTrailing = NSLayoutConstraint(
        item: raceListView as Any, attribute: NSLayoutConstraint.Attribute.leading,
        relatedBy: NSLayoutConstraint.Relation.equal,
        toItem: raceInfoView, attribute: NSLayoutConstraint.Attribute.trailing,
        multiplier: 1, constant: 0)
    landscapeRaceInfoViewBottom = NSLayoutConstraint(
        item: raceInfoView as Any, attribute: NSLayoutConstraint.Attribute.bottom,
        relatedBy: NSLayoutConstraint.Relation.equal,
        toItem: racesView, attribute: NSLayoutConstraint.Attribute.bottom,
        multiplier: 1, constant: 0)
    landscapeRaceListViewTop = NSLayoutConstraint(
        item: raceListView as Any, attribute: NSLayoutConstraint.Attribute.top,
        relatedBy: NSLayoutConstraint.Relation.equal,
        toItem: racesView, attribute: NSLayoutConstraint.Attribute.top,
        multiplier: 1, constant: 0)

    applyOrientationConstraints()
}

Объявление ограничений программно выглядит немного страшно, но на самом деле это довольно просто. Вы можете создать ограничение в вашей раскадровке, просмотреть все значения и скопировать правильные значения в нужное место в коде.

И, наконец, в viewDidLoad примените ограничения с помощью applyOrientationConstraints().

func applyOrientationConstraints() {
    let orient = UIApplication.shared.statusBarOrientation
    switch orient {
    case .portrait:
        NSLayoutConstraint.activate([portraitRaceInfoViewTrailing, portraitRaceInfoViewBottom, portraitRaceListViewLeading])
        NSLayoutConstraint.deactivate([landscapeRaceInfoViewTrailing, landscapeRaceInfoViewBottom, landscapeRaceListViewTop])
        break
    default:
        NSLayoutConstraint.deactivate([portraitRaceInfoViewTrailing, portraitRaceInfoViewBottom, portraitRaceListViewLeading])
        NSLayoutConstraint.activate([landscapeRaceInfoViewTrailing, landscapeRaceInfoViewBottom, landscapeRaceListViewTop])
        break
    }
}

И, наконец, переопределите viewWillTransition, чтобы применить ограничения при изменении ориентации.

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) -> Void in
        self.applyOrientationConstraints()
    }, completion: { (UIViewControllerTransitionCoordinatorContext) -> Void in
        print("rotation completed")
    })
    super.viewWillTransition(to: size, with: coordinator)
}

Ответ 9

мои два цента.. Свифт 5:

(пожалуйста, подключите розетку....)

//
//  ViewController.swift
//  AutoLayoutSampleOnRotation
//
//  Created by ing.conti on 13/09/2019.
//  Copyright © 2019 ing.conti. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var redView: UIView!
    @IBOutlet weak var yellowView: UIView!

    private var red_TopPortrait : NSLayoutConstraint?
    private var red_TopLandscape : NSLayoutConstraint?

    private var red_LeftPortrait : NSLayoutConstraint?
    private var red_LeftLandscape : NSLayoutConstraint?

    private var red_RightPortrait : NSLayoutConstraint?
    private var red_RightLandscape : NSLayoutConstraint?

    private var red_BottomPortrait : NSLayoutConstraint?
    private var red_BottomLandscape : NSLayoutConstraint?

    private var red_HeightPortrait : NSLayoutConstraint?
    private var red_WidthLandscape : NSLayoutConstraint?


    ///
    private var yellow_TopPortrait : NSLayoutConstraint?
    private var yellow_TopLandscape : NSLayoutConstraint?

    private var yellow_LeftPortrait : NSLayoutConstraint?
    private var yellow_LeftLandscape : NSLayoutConstraint?

    private var yellow_RightPortrait : NSLayoutConstraint?
    private var yellow_RightLandscape : NSLayoutConstraint?

    private var yellow_BottomPortrait : NSLayoutConstraint?
    private var yellow_BottomLandscape : NSLayoutConstraint?


    private let H_SpaceBetween = CGFloat(20)
    private let V_SpaceBetween = CGFloat(50)

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.


        redView.translatesAutoresizingMaskIntoConstraints = false
        yellowView.translatesAutoresizingMaskIntoConstraints = false

        buildConstraintsForRed()
        buildConstraintsForYellow()

        applyConstraints()
    }



    final private func buildConstraintsForRed(){

        let portraitTopMargin = CGFloat(70)
        let portraitLeftMargin = CGFloat(70)
        let portraitRightMargin = CGFloat(70)

        let landscapeTopMargin = CGFloat(70)
        let landscapeLeftMargin = CGFloat(70)
        let landscapeBottomMargin = CGFloat(70)

        // TOP P
        red_TopPortrait = NSLayoutConstraint(item: redView as Any,
                                             attribute: .top,
                                             relatedBy: .equal,
                                             toItem: self.view,
                                             attribute: .top,
                                             multiplier: 1,
                                             constant: portraitTopMargin)
        red_TopPortrait!.identifier = "red_TopPortrait"

        // LEFT-Heading P
        red_LeftPortrait = NSLayoutConstraint(item: redView as Any,
                                              attribute: .leading,
                                              relatedBy: .equal,
                                              toItem: self.view,
                                              attribute: .leading,
                                              multiplier: 1,
                                              constant: portraitLeftMargin)
        red_LeftPortrait!.identifier = "red_LeftPortrait"

        // RIGHT - trailing P
        red_RightPortrait = NSLayoutConstraint(item: redView as Any,
                                               attribute: .trailing,
                                               relatedBy: .equal,
                                               toItem: self.view,
                                               attribute: .trailing,
                                               multiplier: 1,
                                               constant: -portraitRightMargin)
        red_RightPortrait!.identifier = "red_RightPortrait"

        // BOTTOM: P
        red_BottomPortrait = NSLayoutConstraint(item: redView as Any,
                                                attribute: .bottom,
                                                relatedBy: .equal,
                                                toItem:  yellowView,
                                                attribute: .top,
                                                multiplier: 1,
                                                constant: -V_SpaceBetween)
        red_BottomPortrait!.identifier = "red_BottomPortrait"

        // HEIGHT: P
        red_HeightPortrait = NSLayoutConstraint(item: redView as Any,
                                          attribute: .height,
                                          relatedBy: .equal,
                                          toItem: self.view,
                                          attribute: .height,
                                          multiplier: 0.3,
                                          constant: 0)
        red_HeightPortrait?.identifier = "red_HeightPortrait"



        //LANDSCAPE
        // TOP L
        red_TopLandscape = NSLayoutConstraint(item: redView as Any,
                                              attribute: .top,
                                              relatedBy: .equal,
                                              toItem: self.view,
                                              attribute: .top,
                                              multiplier: 1,
                                              constant: landscapeTopMargin)
        red_TopLandscape!.identifier = "red_TopLandscape"

        // LEFT-Heading L
        red_LeftLandscape = NSLayoutConstraint(item: redView as Any,
                                               attribute: .leading,
                                               relatedBy: .equal,
                                               toItem: self.view,
                                               attribute: .leading,
                                               multiplier: 1,
                                               constant: landscapeLeftMargin)
        red_LeftLandscape!.identifier = "red_LeftLandscape"


        // RIGHT - trailing L
        red_RightLandscape = NSLayoutConstraint(item: redView as Any,
                                                attribute: .trailing,
                                                relatedBy: .equal,
                                                toItem: yellowView,
                                                attribute: .leading,
                                                multiplier: 1,
                                                constant: -H_SpaceBetween)
        red_RightLandscape!.identifier = "red_RightLandscape"


        // BOTTOM: L
        red_BottomLandscape = NSLayoutConstraint(item: redView as Any,
                                                 attribute: .bottom,
                                                 relatedBy: .equal,
                                                 toItem: self.view,
                                                 attribute: .bottom,
                                                 multiplier: 1,
                                                 constant: -landscapeBottomMargin)
        red_BottomLandscape?.identifier = "red_BottomLandscape"

        // Width L:
        red_WidthLandscape = NSLayoutConstraint(item: redView as Any,
                                          attribute: .width,
                                          relatedBy: .equal,
                                          toItem: self.view,
                                          attribute: .width,
                                          multiplier: 0.3,
                                          constant: 0)
        red_WidthLandscape!.identifier = "red_WidthLandscape"
    }


    final private func buildConstraintsForYellow(){

        let portraitLeftMargin = CGFloat(20)
        let portraitRightMargin = CGFloat(20)
        //let portraitHorizMargin = CGFloat(100)
        let portraitBottomMargin = CGFloat(20)

        let landscaspeTopMargin = CGFloat(20)
        let landscaspeRightMargin = CGFloat(20)
        let landscapeBottomMargin = CGFloat(20)


        // TOP P
        yellow_TopPortrait = NSLayoutConstraint(item: yellowView as Any,
                                             attribute: .top,
                                             relatedBy: .equal,
                                             toItem: redView,
                                             attribute: .bottom,
                                             multiplier: 1,
                                             constant: V_SpaceBetween)
        yellow_TopPortrait!.identifier = "yellow_TopPortrait"

        // LEFT-Heading P
        yellow_LeftPortrait = NSLayoutConstraint(item: yellowView as Any,
                                                 attribute: .leading,
                                                 relatedBy: .equal,
                                                 toItem: self.view,
                                                 attribute: .leading,
                                                 multiplier: 1,
                                                 constant: portraitLeftMargin)
        yellow_LeftPortrait!.identifier = "yellow_LeftPortrait"

        // RIGHT - trailing P
        yellow_RightPortrait = NSLayoutConstraint(item: yellowView as Any,
                                                  attribute: .trailing,
                                                  relatedBy: .equal,
                                                  toItem: self.view,
                                                  attribute: .trailing,
                                                  multiplier: 1,
                                                  constant: -portraitRightMargin)
        yellow_RightPortrait!.identifier = "yellow_RightPortrait"

        // BOTTOM: P
        yellow_BottomPortrait = NSLayoutConstraint(item: yellowView as Any,
                                                   attribute: .bottom,
                                                   relatedBy: .equal,
                                                   toItem: self.view,
                                                   attribute: .bottom,
                                                   multiplier: 1,
                                                   constant: -portraitBottomMargin)
        yellow_BottomPortrait!.identifier = "yellow_BottomPortrait"

        //LANDSSCAPE
        // TOP L
        yellow_TopLandscape = NSLayoutConstraint(item: yellowView as Any,
                                              attribute: .top,
                                              relatedBy: .equal,
                                              toItem: self.view,
                                              attribute: .top,
                                              multiplier: 1,
                                              constant: landscaspeTopMargin)
        yellow_TopLandscape!.identifier = "yellow_TopLandscape"

        // LEFT-Heading L
        yellow_LeftLandscape = NSLayoutConstraint(item: yellowView as Any,
                                               attribute: .leading,
                                               relatedBy: .equal,
                                               toItem: self.redView,
                                               attribute: .trailing,
                                               multiplier: 1,
                                               constant: H_SpaceBetween)
        yellow_LeftLandscape!.identifier = "yellow_LeftLandscape"

        // RIGHT - trailing L
        yellow_RightLandscape = NSLayoutConstraint(item: yellowView as Any,
                                                attribute: .trailing,
                                                relatedBy: .equal,
                                                toItem: self.view,
                                                attribute: .trailing,
                                                multiplier: 1,
                                                constant: -landscaspeRightMargin)
        yellow_RightLandscape!.identifier = "yellow_RightLandscape"

        // BOTTOM: L
        yellow_BottomLandscape = NSLayoutConstraint(item: yellowView as Any,
                                                 attribute: .bottom,
                                                 relatedBy: .equal,
                                                 toItem: self.view,
                                                 attribute: .bottom,
                                                 multiplier: 1,
                                                 constant: -landscapeBottomMargin)
        yellow_BottomLandscape!.identifier = "yellow_BottomLandscape"
    }


    final private  func removeRedConstraints() {
        if let c = red_LeftPortrait  {self.view.removeConstraint(c)}
        if let c = red_LeftLandscape  {self.view.removeConstraint(c)}

        if let c = red_RightPortrait  {self.view.removeConstraint(c)}
        if let c = red_RightLandscape  {self.view.removeConstraint(c)}

        if let c = red_TopPortrait  {self.view.removeConstraint(c)}
        if let c = red_TopLandscape  {self.view.removeConstraint(c)}

        if let c = red_BottomPortrait  {self.view.removeConstraint(c)}
        if let c = red_BottomLandscape  {self.view.removeConstraint(c)}

        if let c = red_HeightPortrait  {self.view.removeConstraint(c)}
        if let c = red_WidthLandscape  {self.view.removeConstraint(c)}



    }


    final private  func removeYellowConstraints() {
        if let c = yellow_LeftPortrait  {self.view.removeConstraint(c)}
        if let c = yellow_LeftLandscape  {self.view.removeConstraint(c)}

        if let c = yellow_RightPortrait  {self.view.removeConstraint(c)}
        if let c = yellow_RightLandscape  {self.view.removeConstraint(c)}

        if let c = yellow_TopPortrait  {self.view.removeConstraint(c)}
        if let c = yellow_TopLandscape  {self.view.removeConstraint(c)}

        if let c = yellow_BottomPortrait  {self.view.removeConstraint(c)}
        if let c = yellow_BottomLandscape  {self.view.removeConstraint(c)}

    }


    final private func applyPortraitConstraint(){
        removeRedConstraints()
        removeYellowConstraints()
        self.view.addConstraint(self.red_LeftPortrait!)
        self.view.addConstraint(self.red_RightPortrait!)
        self.view.addConstraint(self.red_TopPortrait!)
        self.view.addConstraint(self.red_BottomPortrait!)

        self.view.addConstraint(self.red_HeightPortrait!)


        self.view.addConstraint(self.yellow_LeftPortrait!)
        self.view.addConstraint(self.yellow_RightPortrait!)
        self.view.addConstraint(self.yellow_TopPortrait!)
        self.view.addConstraint(self.yellow_BottomPortrait!)
    }

    final private func applyLandscapeConstraint(){
        removeRedConstraints()
        removeYellowConstraints()
        self.view.addConstraint(self.red_LeftLandscape!)
        self.view.addConstraint(self.red_RightLandscape!)
        self.view.addConstraint(self.red_TopLandscape!)
        self.view.addConstraint(self.red_BottomLandscape!)

        self.view.addConstraint(self.red_WidthLandscape!)

        self.view.addConstraint(self.yellow_LeftLandscape!)
        self.view.addConstraint(self.yellow_RightLandscape!)
        self.view.addConstraint(self.yellow_TopLandscape!)
        self.view.addConstraint(self.yellow_BottomLandscape!)
    }




    final private func applyConstraints(){

        let orient = UIApplication.shared.statusBarOrientation

        switch orient {
        case .portrait:
            print("Portrait")
            self.applyPortraitConstraint()
            break
            // Do something

        default:
            print("LandScape")
            // Do something else
            self.applyLandscapeConstraint()
            break
        }

    }






    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {


        coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) -> Void in

            self.applyConstraints()
        }, completion: { (UIViewControllerTransitionCoordinatorContext) -> Void in
            print("rotation completed")
        })

        super.viewWillTransition(to: size, with: coordinator)
    }
}

IN SIMULATOR.......