Last active
June 14, 2022 09:01
-
-
Save megimix/d0bbea45bd3e1e4d615fbd5c30b54da7 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 hidden or 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
how to align left in case?