Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lamb-mei/1e4d22cfc7b055b6c7a1c6ffe5e5ff16 to your computer and use it in GitHub Desktop.
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)
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