Last active
January 22, 2016 23:11
-
-
Save rsattar/6c3fc9382b118244f3df to your computer and use it in GitHub Desktop.
UIImageView which constraints its own height based on its layouted width
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (void) setImage:(UIImage *)image | |
{ | |
[super setImage:image]; | |
if (self.lk_heightConstrainedToAspectWidth && self.image) { | |
CGFloat imageAspectRatio = self.image.size.height / self.image.size.width; | |
// If we haven't constrained ourself, or the constraint needs updating | |
if (!self.aspectRatioHeightConstraint || self.aspectRatioHeightConstraint.multiplier != imageAspectRatio) { | |
[self setNeedsUpdateConstraints]; | |
} | |
} | |
} | |
- (void) updateConstraints | |
{ | |
if (self.lk_heightConstrainedToAspectWidth && self.image) { | |
CGFloat aspectRatioToSet = self.image.size.height / self.image.size.width; | |
if (!self.aspectRatioHeightConstraint || self.aspectRatioHeightConstraint.multiplier != aspectRatioToSet) { | |
// We haven't constrained ourself, or the constraint needs updating | |
// Remove the outdated constraint | |
if (self.aspectRatioHeightConstraint) { | |
[self removeConstraint:self.aspectRatioHeightConstraint]; | |
self.aspectRatioHeightConstraint = nil; | |
} | |
// Create a new constraint based upon the new aspect ratio | |
self.aspectRatioHeightConstraint = [NSLayoutConstraint constraintWithItem:self | |
attribute:NSLayoutAttributeHeight | |
relatedBy:NSLayoutRelationEqual | |
toItem:self | |
attribute:NSLayoutAttributeWidth | |
multiplier:aspectRatioToSet | |
constant:0.0]; | |
[self addConstraint:self.aspectRatioHeightConstraint]; | |
} | |
} else if (self.aspectRatioHeightConstraint) { | |
[self removeConstraint:self.aspectRatioHeightConstraint]; | |
self.aspectRatioHeightConstraint = nil; | |
} | |
[super updateConstraints]; | |
} | |
// In case this is dynamically changed at runtime, update our constraints | |
- (void) setLk_heightConstrainedToAspectWidth:(BOOL)lk_heightConstrainedToAspectWidth | |
{ | |
if (_lk_heightConstrainedToAspectWidth != lk_heightConstrainedToAspectWidth) { | |
_lk_heightConstrainedToAspectWidth = lk_heightConstrainedToAspectWidth; | |
if (self.image != nil) { | |
[self setNeedsUpdateConstraints]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After talking to @Eridius on iOS Folks slack, he suggested setting up an "aspect ratio" constraint (height to width) that just gets set whenever the image is updated. Doing that next...