Search code examples
iosobjective-calignmentuistackview

programmatically change the aligment of a UIStackView does not work properly


What I have:

This is my hierarchy of views:

  • a button named b1 which has an action named "changeAlignment" that is activated Upon touch Up Inside.
  • an UIView named Pview with frame (0,100,414,100).
    • an horizontal UIStackView named S1, with the alignment property set as "center". This stackView has been pinned to the borders of pView.
      • an horizontal UIStackView named S2, with the alignment property set as "Fill" and which has inside two labels.

What I want to do:

I want to change the alignment of S1 from "Center" to "Top" when I touch the button b1.

What I tried

- (void) changeAlignment {
  NSLog(@"P-%li",(long)S1.alignment);
  S1.alignment = UIStackViewAlignmentTop;
  NSLog(@"P-%li",(long)S1.alignment);
  [pView layoutIfNeeded];
}

This sounds obvious but it does not work!!. The funny thing is that it works at some time but suddenly it stops working. Now when I tap b1, the alignment of S1 changes but visually it does not change at all.

I've trying with [self.view setNeedsLayout] [self.view layoutIfNeeded] and even [S1 layoutIfNeeded] and none of this have work.

What I'm doing wrong??..How it is even possible that it actually works and suddenly stop working!!??

Can anybody please help me??...this is drive me crazy.


Solution

  • I think the answer of this is the same as in How to programmatically animate the alignment property of an UIStackView in ios 9.

    The explanation for this behaviour is the following:

    1. a stackView automatically generates the constraints it needs in order to layout its arranged subviews,
    2. defining a horizontal stackview S1 with another stackView S2 as an arranged subview of S1, make S1 to create some constraints that (a) are not affected, (b) are not recomputed or (c) are recomputed but remains the same, when you changed the alignment property of S1 from Center to Top and viceversa. So, since the constraints S1 automatically generated are not affected or they do not change at all after changing the alignment property, the UI does not reflect any change and there is no animation either.