Autolayout: change constraint multiplier

Mon, 03. Aug 2015

Categories: en development Tags: Apple Autolayout iOS NSLayoutConstraint Objective C

the NSLayoutConstraint multiplier property is read-only. But if you need to change it, you can replace the constraint with a modified clone like

@implementation NSLayoutConstraint(ChangeMultiplier)
// visal form center http://stackoverflow.com/a/13148012/349514
-(NSLayoutConstraint *)constraintWithMultiplier:(CGFloat)multiplier
{
  return [NSLayoutConstraint
    constraintWithItem:self.firstItem
    attribute:self.firstAttribute
    relatedBy:self.relation
    toItem:self.secondItem
    attribute:self.secondAttribute
    multiplier:multiplier
    constant:self.constant];
}
@end

and replace it like

NSLayoutConstraint *c = [self.constraintToChange constraintWithMultiplier:0.75];
  [self.view removeConstraint:self.constraintToChange];
  [self.view addConstraint:self.constraintToChange = c];
  [self.view layoutIfNeeded];