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?

Stefan
  • 5,203
  • 8
  • 27
  • 51
BlackM
  • 3,927
  • 8
  • 39
  • 69
  • if you add the constraint in storyboard, you can directly drag it to your class – Surely Nov 28 '15 at 12:36
  • 2
    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. – Surely Nov 28 '15 at 12:40
  • 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 UI – BlackM Nov 28 '15 at 12:59
  • 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 it – BlackM Nov 28 '15 at 13:03

2 Answers2

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.

Surely
  • 1,649
  • 16
  • 23
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];
      }
    }];
keshav vishwkarma
  • 1,832
  • 13
  • 20