Created
October 16, 2014 21:29
-
-
Save Antol/e42359f12340abe072d6 to your computer and use it in GitHub Desktop.
UIImageView with aspect fit working with autolayout
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
// | |
// 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 |
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
// | |
// 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