JSB
JSB

Reputation: 95

Swift change aspect ratio constraint programmatically

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

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:

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

Upvotes: 4

Views: 6494

Answers (1)

Rakesha Shastri
Rakesha Shastri

Reputation: 11242

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()
}

Upvotes: 3

Related Questions