Set UIImageView AspectRatio constraint programmatically in swift 3

Shariif Islam picture Shariif Islam · Jun 21, 2017 · Viewed 14.5k times · Source

I have an UIImageView in storyboard which AspectRatio is 1:1, that I want to change to 2:1 programmatically in ViewController in some cases. I create reference of that constraint in ViewController but unable to set the constraint.

Answer

Jugal K Balara picture Jugal K Balara · Jun 21, 2017

You can change constraint programmatically in swift 3

let aspectRatioConstraint = NSLayoutConstraint(item: self.YourImageObj,attribute: .height,relatedBy: .equal,toItem: self.YourImageObj,attribute: .width,multiplier: (2.0 / 1.0),constant: 0)
self.YourImageObj.addConstraint(aspectRatioConstraint)