Search code examples
iosswiftautolayout

Swift change aspect ratio constraint programmatically


We have a MainStoryBoard with a UIButton and a UIView foo with 4 constraints:

  • foo top to superView top
  • foo leading to superView leading
  • foo trailing to superView trailing
  • foo aspectRatio 16:9

The desired behavior of the button should be that it changes the foo constraints so foo will expand to full screen, and if pressed again it should have the previous aspect ratio, 16:9.

I've tried to do this with the constraint's IBOutlet following this steps:

  • on expand:
    • remove aspectRatio constraint from foo
    • add a foo bottom constraint to superView bottom
  • on collapse:
    • remove foo bottom constraint to superView bottom
    • add aspectRatio constraint to foo

I also played with heights and nothing. Thanks in advance.


Solution

  • Your initial constraints should look like this.

    NSLayoutConstraint.activate([
        foo.leadingAnchor.constraint(equalTo: superView.leadingAnchor),
        foo.trailingAnchor.constraint(equalTo: superView.trailingAnchor),
        foo.topAnchor.constraint(equalTo: superView.topAnchor)
    ])
    
    let collapsedConstraint = foo.heightAnchor.constraint(equalTo: foo.widthAnchor, multiplier: 9/16)
    let expandedConstraint = foo.bottomAnchor.constraint(equalTo: superView.bottomAnchor)
    collapsedConstraint.isActive = collapsed
    expandedConstraint.isActive = !collapsed
    

    And the method that is triggered should change the constraints like this.

    @objc func tapAction() {
        collapsedConstraint.isActive = collapsed
        expandedConstraint.isActive = !collapsed
        superView.layoutIfNeeded()
    }