jdog
jdog

Reputation: 10759

Unable to simultaneously satisfy constraints when setting them programatically

In my storyboard I set the following constraints.

left side constraint for a view = 9;
right side constraint for a view = 9;
(so I have 9 pixels space on both sides)

These constraints are set as constants in my VC.

confirmLocationViewLeftsideConstraint
confirmLocationViewRightsideConstraint

Now when my app loads I want this view off screen and then animate it on screen so I set the constraints via code.

self.confirmLocationViewLeftsideConstraint.constant = 400.0f;
self.confirmLocationViewRightsideConstraint.constant = -409.0f;

But this causes the app to crash with the following error:

    Unable to simultaneously satisfy constraints.
        Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
    (

        "<NSLayoutConstraint:0x175f1bb0 H:|-(400)-[UIView:0x175f0080]   (Names: '|':UIView:0x175f1be0 )>",
        "<NSLayoutConstraint:0x1761a6b0 H:[UIView:0x175f0080]-(9)-|   (Names: '|':UIView:0x175f1be0 )>",
        "<NSAutoresizingMaskLayoutConstraint:0x1b387bf0 h=--& v=--& H:[UIView:0x175f1be0(320)]>"
    )

To me this is saying you can't set the confirmLocationViewLeftsideConstraint to 400 when the right is 9. But my next line of code above is going to set the confirmLocationViewRightsideConstraint to -409 so it should work, but I can't set both of these at the exact same time.

Is there a better way to achieve this sliding a view on and off? Or a better way to set them in code? I need to set the layout constraints in storyboard as I its a very detailed View with over 70 constraints to keep spacing.

Upvotes: 0

Views: 168

Answers (1)

Ken Thomases
Ken Thomases

Reputation: 90521

To my mind, having two constraints that you have to update in sync suggests you're using the wrong constraints. You could have a constraint for the leading edge and then a constraint making the view's width equal to the width of the superview - 18. That way, you only have to adjust the leading constraint's constant and both edges move as a consequence.

Another approach is to remove both constraints from the superview (making sure that your references are strong, so the constraints aren't released), adjust them, and then re-add them.

The former approach makes animation simpler, though, since you just have to animate the one constraint's constant (instead of animating the layout).

Upvotes: 1

Related Questions