Forked from megimix/UIImageView+topAlignmentAndAspectFit
Created
December 15, 2018 16:25
-
-
Save lamb-mei/1e4d22cfc7b055b6c7a1c6ffe5e5ff16 to your computer and use it in GitHub Desktop.
UIImageView with Aspect Fit and Alignment To Top. thanks to (http://stackoverflow.com/a/27569222/1267174)
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
extension UIImageView { | |
func topAlignmentAndAspectFit(to view: UIView) { | |
self.contentMode = .scaleAspectFill | |
self.translatesAutoresizingMaskIntoConstraints = false | |
view.addSubview(self) | |
self.addConstraints( | |
[NSLayoutConstraint(item: self, | |
attribute: .height, | |
relatedBy: .equal, | |
toItem: self, | |
attribute: .width, | |
multiplier: self.frame.size.height / self.frame.size.width, | |
constant: 0.0)]) | |
view.addConstraints( | |
[NSLayoutConstraint(item: self, | |
attribute: .centerX, | |
relatedBy: .equal, | |
toItem: view, | |
attribute: .centerX, | |
multiplier: 1.0, | |
constant: 0.0)]) | |
view.addConstraints( | |
[NSLayoutConstraint(item: self, | |
attribute: .width, | |
relatedBy: .equal, | |
toItem: view, | |
attribute: .width, | |
multiplier: 1.0, | |
constant: 0.0)]) | |
view.addConstraints( | |
NSLayoutConstraint.constraints(withVisualFormat: "V:|[imageView]", | |
options: .alignAllTop, | |
metrics: nil, | |
views: ["imageView": self])) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment