3

I'm currently trying to change the axis on a stack view based on the orientation of the device. Everything works fine while the phone is vertical, but as soon as I go horizontal my constraints break.

Currently, I have the blue view and the orange view in a vertical stack view. I have the stack view pinned to the leading, top and trailing edge of the super view. I have the bottom of the stack view pinned to the black view. Because the child views within the stack view are not proportional I've set the blue view to a constant height of 70. The stack view is set with the following:

  1. Alignment - Fill
  2. Distribution - Fill
  3. Axis - Vertical

I've discovered whats breaking my constraints when changing the orientation to horizontal, it's the constant height set on the blue view. To combat this I create an IBOutlet of the blue views height constraint. When the phone is rotated I was deactivating the constraint:

 override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.current.orientation.isLandscape {
        blueViewHeight.isActive = false
        stackView.axis = .horizontal
    } else {
        blueViewHeight.isActive = true
        stackView.axis = .vertical
    }
}

This did not work. My constraints still broke. I then created a width constraint for the blue view (thinking the stack view needed the width while horizontal). I was activating/deactivating the height/width constraint for the blue view based off of the orientation. Alas, this also resulted in broken constraints (in other words my views are strewn all over the place).

The images I have below is what I'm trying to achieve. What should I be setting, or not setting, to get the desired look.

Vertical View

Horizontal View

WBuck
  • 5,162
  • 2
  • 25
  • 36
  • I eventually gave up on using a stack view for this. I just wasn't able to get it to work. Instead I created a list of vertical constraints and horizontal constraints. Depending on the orientation of the screen I activate/deactivate the constraints contained in their corresponding arrays. – WBuck Mar 12 '18 at 13:06

1 Answers1

3

To achieve this you should use 2 stack views, one containing the blue and orange views I´ll call this StackView1, and the second one containing the StackView1 and the black view I´ll call this StackView2.

view hierarchy

After this is just matter of playing with size classes. On StackView1, I´ll set the axis of the stackView to horizontal when the phone is on landscape:

Axis

and constraints between views, also keeping in mind size classes:

Between Blue and Orange Views:

bo1 bo2

And finally between Blue and Black views:

bb2 bb1

NOTE: In both stackViews I'm using alignment: fill and distribution: fill