Set UIImageView AspectRatio constraint programmatically in swift 3
Asked Answered
I

3

11

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.

Ioab answered 21/6, 2017 at 6:12 Comment(1)
After setting up the constraint, call view.layoutIfNeeded().Thyroid
A
18

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)
Another answered 21/6, 2017 at 6:41 Comment(0)
G
18

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
Gilli answered 1/1, 2018 at 22:10 Comment(0)
D
-1

Set the multiplier of the constraint to 0.5 or 2 depending on your constraint condition, It'll become 2:1

Darnelldarner answered 21/6, 2017 at 6:15 Comment(3)
Thanks for your answer, but i am not clear about it. I tried to set constraints like this, 'cons_coverImageRatio.constant.multiply(by: 0.5)'. But its not working. Would you show me how to set that constraintIoab
simple use like self.imageAspectConstraint.multiplier = 0.5, and then call self.imageView.layoutIfNeeded()Darnelldarner
multiplier is a get property so can't assign itChump

© 2022 - 2024 — McMap. All rights reserved.