0

I would like to animate, in code, a constraint that is created in IB. I want to find the constraint between the bottom LayoutGuide and the bottom edge of my UIView.

The constraint instances are remarkably opaque: firstItem and secondItem are AnyObject so there is a lot of casting. And apart from doing a string compare on _stdlib_getTypeName(), it's hard to see how I will decide which constraints involve the LayoutGuides.

Or should I just delete all constraints and re-create them on the fly? (But then what's the point of IB? Since my storyboard uses auto layout, I am obliged to add constraints in IB anyway.)

Andrew Duncan
  • 3,553
  • 4
  • 28
  • 55
  • 3
    Why don't you make an IBOutlet to it when you create it? – rdelmar Jan 17 '15 at 22:01
  • IBOutlet is definitely the way to go. If you insist on searching for them, take a look at this question: http://stackoverflow.com/q/27791597/1630618 – vacawama Jan 17 '15 at 22:30

2 Answers2

1

Click on the constraint in Interface Builder and create an IBOutlet for it, just as you would for a button, text view, etc.

You can also find it at runtime using something like this:

NSLayoutConstraint *desiredConstraint;
for (NSLayoutConstraint *constraint in putYourViewHere.constraints) {
    if (constraint.firstAttribute == NSLayoutAttributeHeight) { // Or whatever attribute you're looking for - you can do more tests
        desiredConstraint = constraint;
        break;
    }
}
SevenBits
  • 2,836
  • 1
  • 20
  • 33
  • Thank you! Yes, I was doing something like the code you suggested, but I was still getting several constraints, that I had to filter further based on the first/secondItem. And how to tell that the Item is a LayoutGuide? Bla bla. Much better to use IB and outlets the way they were intended! – Andrew Duncan Jan 17 '15 at 23:07
0

This should be simple. As has already been stated, create an IBOutlet for the constraint you want to animate:

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *verticalSpaceLayoutConstraint;

Then when you want to animate it (Also see: How do I animate constraint changes?) force a layout pass if needed in your view that has the constraint, update your constraint to value you want, do your UIView animation and force layout passes as needed for the animation's duration:

- (void)moveViewSomewhere { 
    [self.view layoutIfNeeded];

    _verticalSpaceLayoutConstraint.constant = 10;  // The value you want your constraint to have when the animation completes.
    [UIView animateWithDuration:1.0
        animations:^{
            [self.view layoutIfNeeded];
        }];
}
Community
  • 1
  • 1
Aaron
  • 7,055
  • 2
  • 38
  • 53