Search code examples
iosswiftswift3nslayoutconstraint

Aspect ratio constraint not getting altered


I have two kinds of image 1.Square and other 2. Images with ratio 3:4. And I get information about the aspect ratio of incoming image in advance(which is in currentImageAspectRatio). I want to handle both kind of images in one UIImageView.

In Storyboard

I have added both 1:1 and 3:4 constraints to my imageView, and then unchecked Installed for 3:4 constraint.

In Code

My viewDidLoad has

if currentImageAspectRatio == .square{
    // Already Square
} else {
    NSLayoutConstraint.deactivate([squareImageConstraint])
    imageView.addConstraint(threeByFourImageConstraint)
    self.view.layoutIfNeeded()
}

But this doesn't seem to work. I also tried to put same code in viewWillAppear: but that too didn't work.

I am confused if there is something wrong I am doing.

And also I need suggestion on where is the most ideal place to do such stuff like altering constraints(I was thinking to use viewWillLayoutSubviews).


Solution

  • Calling the same code from viewDidLayoutSubviews worked for me.