Search code examples
iosswiftuiviewanimationuistackviewsubviews

View as a subview of UIStackView cannot be rotated


I have a UIStackView, in it there's a subView called A. I want to rotate the view A. But nothing happened. I can rotate the A's layer, it's OK. So how to make animation of subviews of UIStackView?


Solution

  • Once you add an "arranged subview" to a stack view, its frame is automatically managed by the constraints added implicitly by the stack view. While you could hypothetically add additional constraints which could be animated, there's no set of constraints that would allow you to accomplish a rotation.

    One solution would be to nest another view inside the one that's being managed by the stack. You could then override layoutSubviews in the outer view to opt out of auto layout for the inner view, so you can manage its rotation. Whatever updates that you make there to the inner view's frame could then be placed inside an animation block.

    EDIT:

    According to the docs for the transform property of UIView, "In iOS 8.0 and later, the transform property does not affect Auto Layout. Auto layout calculates a view’s alignment rectangle based on its untransformed frame." That seems to imply that a rotation should work even in the presence of auto layout constraints. That said, my guess is that transforming the view is really just a convenience for transforming the underlying layer.