4

Problem

In UI I have some view which content is stretchable but should conserve some aspect ratio. This aspect ratio changes during run-time and views layout should be updated when some property describing aspect ratio changes.

I've exposed NSLayoutConstraint, but its property used for aspect ratio: multiplier is read only. What is more funny similar property constant can be changed.

Possible solutions

  1. I could just use constraint which fixes width or height and calculate it based on expected ratio, but this requires extra boiler plate code which will react on geometry/layout changes and I prefer to avoid this.
  2. I could experiment with intrisicContentSize and sizeThatFits: but I'm not sure how this should be used with NSLayoutConstraint
Catalina T.
  • 3,456
  • 19
  • 29
Marek R
  • 32,568
  • 6
  • 55
  • 140
  • 1
    Take a look at this answer. I got around the fact that the multiplier couldn't be modified by adding/removing the constraint from code: http://stackoverflow.com/a/27592375/1630618 – vacawama May 13 '15 at 14:56
  • looks promising I will try this. – Marek R May 13 '15 at 20:36

1 Answers1

12

Ok I'm whining to much. Removing and recreating constraint is not such a big problem (thanks @vacawama):

- (void)updateASpectRatio: (float)aspectRatio {
    // self.aspectRatioConstraint - has to be a strong reference
    [self.aspectRatioView removeConstraint: self.aspectRatioConstraint];
    self.aspectRatioConstraint = [NSLayoutConstraint constraintWithItem: self.aspectRatioConstraint.firstItem
                                                              attribute: self.aspectRatioConstraint.firstAttribute
                                                              relatedBy: self.aspectRatioConstraint.relation
                                                                 toItem: self.aspectRatioConstraint.secondItem
                                                              attribute: self.aspectRatioConstraint.secondAttribute
                                                             multiplier: self.aspectRatioView.aspectRatio
                                                               constant: 0.0];
    [self.aspectRatioView addConstraint: self.aspectRatioConstraint];
}
Marek R
  • 32,568
  • 6
  • 55
  • 140