Skip to content

Instantly share code, notes, and snippets.

@rsattar
Last active January 22, 2016 23:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsattar/6c3fc9382b118244f3df to your computer and use it in GitHub Desktop.
Save rsattar/6c3fc9382b118244f3df to your computer and use it in GitHub Desktop.
UIImageView which constraints its own height based on its layouted width
- (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];
}
}
}
@rsattar
Copy link
Author

rsattar commented Jan 22, 2016

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...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment