简体   繁体   中英

Find in code a layout constraint created in IB

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.)

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;
    }
}

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];
        }];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM