j2emanue
j2emanue

Reputation: 62539

iOS - changing constraint relation programmatically

given the following constraint in ios programmatically:

IBOutlet NSLayoutConstraint *myConstraint;

this constraint is linked in interfacebuilder to the following details: enter image description here

How do I change the relation attribute programmatically. I tried to look up for a method called setRelation but I don't see it.

Upvotes: 15

Views: 12754

Answers (2)

Erhan Demirci
Erhan Demirci

Reputation: 4209

You can do like that :

  [self.view addConstraint:[NSLayoutConstraint
                                 constraintWithItem:self.yellowView
                                 attribute:NSLayoutAttributeWidth
                                 relatedBy:NSLayoutRelationEqual
                                 toItem:self.redView
                                 attribute:NSLayoutAttributeWidth
                                 multiplier:0.75
                                 constant:0.0]];

Upvotes: 4

i_am_jorf
i_am_jorf

Reputation: 54610

According to the documentation, relation is read-only.

What you will need to do, I suspect, is to set

self.myConstraint.active = NO;

Then make a new NSLayoutConstraint programmatically using:

+ constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:

And in the process copying values you want to keep, and replacing the relation.

Then add it to the view hierarchy where appropriate.

Upvotes: 17

Related Questions