iOS 8 - Find constraints for a UIView with identifier
Asked Answered
O

2

7

I am trying to change a constraint for an ImageView for iPhone 4S,5,5S in viewDidLoad:

for (NSLayoutConstraint *constraint in logoImage.constraints) {
    if ([constraint.identifier isEqualToString:@"logoTopIdentifier"]) {
        constraint.constant=10;
    }
}

It seems that it's not even iterating in the loop. Is there any other way to get a specific constraint with identifier?

Omit answered 28/11, 2015 at 12:26 Comment(4)
if you add the constraint in storyboard, you can directly drag it to your classWhitefish
you know how to connect a uibutton in storyboard to your viewcontroller class? You can do it same way to connect the constraint to your viewcontroller class.Whitefish
Cool I didn't know about that. So after creating the reference and changing the constant I notice that it didn't update anything in UIOmit
I manage to make it work by recreating the constraint. for some reason constant was set only to wChR. Now it's working. Please post it as answer so I can accept itOmit
W
4

You can connect the constraint in storyboard to your view controller class same as connecting a UI element.

Just find the constraints in your storyboard, make the workspace into split view, and drag the constraint to your corresponding view controller class.

Sometimes if you want to animate the position change, you can update the constraint like:

self.theConstraint?.constant = 100 
self.view.setNeedsUpdateConstraints()
UIView.animateWithDuration(0.7) { () -> Void in
    self.view.layoutIfNeeded()
}

block.

That is it.

Whitefish answered 28/11, 2015 at 13:14 Comment(0)
M
2

Here is the KVConstraintExtensionsMaster library by which you can access the any constant from a view based on the NSLayoutAttribute. No matter whether that constraint added Programmatically or from Interface Builder.

 [self.logoImage accessAppliedConstraintByAttribute:NSLayoutAttributeTop completion:^(NSLayoutConstraint *expectedConstraint){
        if (expectedConstraint) {
            expectedConstraint.constant = 10;

            /* for the animation */ 
            [self.logoImage  updateModifyConstraintsWithAnimation:NULL];
      }
    }];
Malar answered 29/11, 2015 at 18:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.