Search code examples
iosobjective-cautolayoutconstraints

auto layout modify multiplier of constraint programmatically


How can I modify the multiplier of a constraint programmatically? I have set the following:

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_button attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:0.5 constant:0.0]];

and I need to modify it to this:

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_button attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0.0]];

Solution

  • As others said, you have to delete the old one and add a new one. If you do not want to store it as a property, just set identifier and search to get it later

    -(NSLayoutConstraint *)constraintWithIndientifer:(NSString *)identifer InView:(UIView *)view{
        NSLayoutConstraint * constraintToFind = nil;
        for (NSLayoutConstraint * constraint in view.constraints ) {
            if([constraint.identifier isEqualToString:identifer]){
                constraintToFind = constraint;
                break;
            }
        }
        return constraintToFind;
    }
    

    Then

    NSLayoutConstraint * constraint = [NSLayoutConstraint constraintWithItem:self.yellowView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:0.5 constant:0.0];
    constraint.identifier = @"1234";
    [self.view addConstraint:constraint];
    

    Then you can get this

    NSLayoutConstraint * constraint = [self constraintWithIndientifer:@"1234" InView:self.view];