Skip to content

Instantly share code, notes, and snippets.

@RichFell
Created November 23, 2015 19:38
Show Gist options
  • Save RichFell/ab010740ed5ef96fe5c5 to your computer and use it in GitHub Desktop.
Save RichFell/ab010740ed5ef96fe5c5 to your computer and use it in GitHub Desktop.
Programmatic vertical, aspect ratio, and horizontally centered constraints
imageView.frame = self.frame
imageView.image = defaultImage
imageView.translatesAutoresizingMaskIntoConstraints = false
addSubview(imageView)
let views: [String: AnyObject] = ["imageView": imageView]
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[imageView]|",
options: .AlignAllCenterX,
metrics: nil,
views: views)
addConstraints(verticalConstraints)
let centerXConstraint = NSLayoutConstraint(item: imageView,
attribute: .CenterX,
relatedBy: .Equal,
toItem: self,
attribute: .CenterX,
multiplier: 1.0,
constant: 0.0)
addConstraint(centerXConstraint)
let aspectRatio = NSLayoutConstraint(item: imageView,
attribute: .Width,
relatedBy: .Equal,
toItem: imageView,
attribute: .Height,
multiplier: 2.0/3.0,
constant: 0.0)
imageView.addConstraint(aspectRatio)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment