Search code examples
iosobjective-cios7autolayout

Trying to move image with UILabel based on text length, constraints do not work


I'm trying to have image align with text label, like so:

enter image description here

To do this I use constraints. I bind the arrow to the right edge, label right side to arrow, and image right side to label left side. Here is the code:

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.disclosureIndicator attribute:NSLayoutAttributeRight
                                                          relatedBy:NSLayoutRelationEqual toItem:self.view
                                                          attribute:NSLayoutAttributeRight multiplier:1.0 constant:-15.0]];

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.purposeLabel attribute:NSLayoutAttributeRight
                             relatedBy:NSLayoutRelationEqual toItem:self.disclosureIndicator
                             attribute:NSLayoutAttributeLeft multiplier:1.0 constant:-10.0]];

NSLayoutConstraint *imgConstraint = [NSLayoutConstraint constraintWithItem:self.purposeImage attribute:NSLayoutAttributeRight
                                                                 relatedBy:NSLayoutRelationEqual toItem:self.purposeLabel
                                                                 attribute:NSLayoutAttributeLeft multiplier:1.0 constant:-4.0];
[self.view addConstraint:imgConstraint];

But when I try to reduce label text length and sizeToFit, it doesn't work, that can be seen from frames:
enter image description here

If I reduce imgConstraintpriority to less then 250 the sizeToFit actually works, label frame changes, but the image does not move at all.

What can I do to fix this?


Solution

  • I forgot to remove the autoresizing constraints, like so:

    self.purposeImage.translatesAutoresizingMaskIntoConstraints = NO;
    

    when I did this, everything worked.