Yi-An
Yi-An

Reputation: 113

Swift change heightAnchor programatically (no storyboard)

I'm new in swift, recently I want to change my heightAnchor programmatically. I have looked up some solutions on stack overflow but most of them are using IBOutlet in storyboard. My question is, if there exists a constraint already, is there any simple way to just update a new constraint?

for example

something.translatesAutoresizingMaskIntoConstraints = false
something.widthAnchor.constraint(equalToConstant: 50).isActive = true // original constraint
something.widthAnchor.constraint(equalToConstant: 100).isActive = true // want to override this one

Upvotes: 1

Views: 596

Answers (2)

Sandeep Bhandari
Sandeep Bhandari

Reputation: 20379

If you have access to original constraint, hold a strong reference to it and update its constant value directly

declare a variable as

var somethingWidthConstraint:NSLayoutConstraint? = nil

and wherever you are setting this constraint originally, hold a strong reference to it

self.somethingWidthConstraint = something.widthAnchor.constraint(equalToConstant: 50)
self.somethingWidthConstraint.isActive = true 

whenever you need to change its constant simply say

self.somethingWidthConstraint?.constant = 100
self.view.layoutIfNeeded()

In order for your view to accept this value and update its frame immediately (without having to wait for next UI render cycle), you might have to call self.view.layoutIfNeeded and if you wanna animate this change you can always wrap it inside UIView.animate

UIView.animate(withDuration: 0.1) {
   self.view.layoutIfNeeded()
}

Thats all

Upvotes: 2

Johannes Maximilian
Johannes Maximilian

Reputation: 77

Try to set the old constraint to false before setting the new one.

something.translatesAutoresizingMaskIntoConstraints = false
something.widthAnchor.constraint(equalToConstant: 50).isActive = true
something.widthAnchor.constraint(equalToConstant: 50).isActive = false 
something.widthAnchor.constraint(equalToConstant: 100).isActive = true

Upvotes: 1

Related Questions