Skip to content

Instantly share code, notes, and snippets.

@megimix
Last active June 14, 2022 09:01
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
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)
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]))
}
}
@rjind1002
Copy link

how to align left in case?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment