pete
pete

Reputation: 2046

How to programmatically change button size without accumulating a huge number of constraints?

I tested the viability of modifying constraints with the following code

sortButton.widthAnchor.constraint(equalToConstant: 5.0).isActive = true
sortButton.widthAnchor.constraint(equalToConstant: 500.0).isActive = true

I thought the 500 would override the 5. However, the console said there was a conflict, and it would break the 500 constraint to stay with the width of 5. I know I can disable the 5.0 one by setting "isActive" to false. However, this isn't the same as actually removing the old constraint. This would be a problem if I keep changing the button size to arbitrary values over the course of running an app. The number of constraints will just keep growing and growing endlessly. What's the right way to change the button size an arbitrary number of times? I tried using the frame as well, and that had no effect.

Upvotes: 0

Views: 28

Answers (1)

RIshabh Shukla
RIshabh Shukla

Reputation: 36

You can make refrence of widthanchor like

weak var widthConstraint: NSLayoutConstraint? 
widthConstraint = sortButton.widthAnchor.constraint(equalToConstant: 5.0)

Now you can manipulate this variable

widthConstraint?.isActive = true

or

widthConstraint?.constant = 500

if in UIStackView

yourStackView.layoutIfNeeded()

Upvotes: 1

Related Questions