Skip to content

Instantly share code, notes, and snippets.

@Antol
Created October 16, 2014 21:29
Show Gist options
  • Save Antol/e42359f12340abe072d6 to your computer and use it in GitHub Desktop.
Save Antol/e42359f12340abe072d6 to your computer and use it in GitHub Desktop.
UIImageView with aspect fit working with autolayout
//
// APAspectFitImageView.h
// autolayout
//
// Created by Antol Peshkov on 16.10.14.
// Copyright (c) 2014 Antol Peshkov. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface APAspectFitImageView : UIImageView
@end
//
// APAspectFitImageView.m
//
// Created by Antol Peshkov on 16.10.14.
// Copyright (c) 2014 Antol Peshkov. All rights reserved.
//
#import "APAspectFitImageView.h"
@interface APAspectFitImageView ()
@property (nonatomic, strong) NSLayoutConstraint *aspectRatio;
@end
@implementation APAspectFitImageView
- (void)awakeFromNib
{
if (self.contentMode == UIViewContentModeScaleAspectFit) {
[self updateAspectRatioWithImage:self.image];
}
}
- (void)setImage:(UIImage *)image
{
[super setImage:image];
if (self.contentMode == UIViewContentModeScaleAspectFit) {
[self updateAspectRatioWithImage:image];
}
}
- (void)updateAspectRatioWithImage:(UIImage *)image
{
if (self.aspectRatio) {
[self removeConstraint:self.aspectRatio];
}
CGFloat aspectRatioValue = image.size.height / image.size.width;
self.aspectRatio = [NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeWidth
multiplier:aspectRatioValue
constant:0.f];
[self addConstraint:self.aspectRatio];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment