6

I have a UITableViewCell subclass laid out using AutoLayout, and I’d like a small animation in which the image view transforms, grows a bit and shrinks back.

At present, due to the constraints, the labels on the right side of the image are moving too (as they should be).

I’d like a quick and easy means to temporarily say “leave those labels where they currently are while this animation is running”. Is that something I can do without needing to remove and re-add those constraints, which is a lot of hassle?

Luke
  • 9,512
  • 15
  • 82
  • 146

2 Answers2

6

Starting in iOS 8 NSLayoutConstraints now have an active property that you can change myConstraint.active = NO;. This removes the constraint, while setting this value to YES will [re]add it:

Activating or deactivating the constraint calls addConstraint: and removeConstraint: on the view that is the closest common ancestor of the items managed by this constraint. Use this property instead of calling addConstraint: or removeConstraint: directly. source

Additionally, there are two new class methods activateConstraints: and deactivateConstraints: that take an array of constraints (NSArray<NSLayoutConstraint>), so that can be helpful, especially if you have an IBOutletCollection with constraints.

[NSLayoutConstraint deactivateConstraints:myConstraints];

Firo
  • 15,448
  • 3
  • 54
  • 74
1

There's no API to say "leave these views here", temporarily disabling some parts of the autolayout. There are several possible solutions:

  • remove your constraints during animation
  • arrange your constraints differently (making them to a superview of the image view, for example, or having them only depend on the center of the image view)
  • override layoutSubviews of a container view to stick your labels back where you want them after autolayout runs in [super layoutSubviews] (or remove the transform of your image view, run autolayout and then put it back)
  • subclass your image view and override frameForAlignmentRect: and alignmentRectForFrame: to get autolayout to use the untransformed frame for alignment purposes.

More details and suggestions are available in the answers here, which is a similar question of how to make transforms and autolayout play together: How do I adjust the anchor point of a CALayer, when Auto Layout is being used?

Community
  • 1
  • 1
Jesse Rusak
  • 56,530
  • 12
  • 101
  • 102
  • This is a great answer, but thankfully I didn’t need it. I used a `CABasicAnimation` in place of a UIView animation, since those don’t trigger layout changes. – Luke Jul 07 '14 at 13:12
  • 1
    @lukech That is one option, but be careful, as if anything else causes a layout during your animation, you'll be back to the same bug you started with. – Jesse Rusak Jul 07 '14 at 13:12