Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set UIImageView AspectRatio constraint programmatically in swift 3

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.

like image 779
Shariif Islam Avatar asked Jun 21 '17 06:06

Shariif Islam


1 Answers

As it's stated in Apple's guide, there're three ways to set constraints programmatically:

  • You can use layout anchors
  • You can use the NSLayoutConstraint class
  • You can use the Visual Format Language

The most convenient and fluent way to set constraints is using Layout Anchors.

It's just one line of code to change aspect ratio for your ImageView

imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: 1.0/2.0).isActive = true

Result View

To avoid "[LayoutConstraints] Unable to simultaneously satisfy constraints." you should add reference to your ImageView's height constraint then deactivate it:

heightConstraint.isActive = false
like image 131
Eugene Brusov Avatar answered Nov 23 '22 11:11

Eugene Brusov