Modify constraint programmatically Swift

Viewed 34120

I have the following view controller in my storyboard :

storyboard_mainVC

It will always have 6 image views that are, by default, equal in widths and heights. Each image view is constrained to the superview with : "equal heights" and a multiplier of 1/2.

However, before I load images inside, I read a property that gives me the desired height for an image (width will never be modified).

So my interface (at runtime) can look like this :

second_interface

I think I need to modify the multiplier constant but it's read-only.

I saw posts saying that we can update the constant property of the constraint but it's in points, I need it to work on every device.

Now what would you recommend ? Should I remove the constraint and add a new one ? If I don't remove it and try to apply a new height constraint, will it be removed automatically for me ?

Do I have to use pods like snapkit to do the job ?

Thanks for your help.

EDIT

Here is the code I tried, but did not succeeded :

        for (index, (drawing, ratio)) in drawingElements.enumerate() {
            drawingViews[index].image = UIImage(named: drawing)
            // update height constraint if ratio is different than defaut ratio of 1/2
            if ratio != 0.5 {
                heightConstraints[index].active = false
                let newHeightConstraint = NSLayoutConstraint(item: drawingViews[index], attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Height, multiplier: ratio, constant: 0)
                drawingViews[index].addConstraint(newHeightConstraint)
                self.view.layoutIfNeeded()
            }
        }

Am I doing it wrong ? I am unsure about the new height constraint though

3 Answers
Related