Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically disable auto-layout constraint

Tags:

Is there any programatic way to temporarily disable an auto-layout constraint? I do not want that constraint to be considered for a certain period of time at all until I need it again.

like image 633
TheNotSoWise Avatar asked Sep 24 '14 15:09

TheNotSoWise


People also ask

What is Autolayout in Swift?

Auto Layout constraints allow us to create views that dynamically adjust to different size classes and positions. The constraints will make sure that your views adjust to any size changes without having to manually update frames or positions.

How do I enable constraints in Swift?

addConstraint(constY); var constW:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute. Width, relatedBy: NSLayoutRelation. Equal, toItem: new_view, attribute: NSLayoutAttribute. Width, multiplier: 1, constant: 0); self.


2 Answers

When developing for iOS 8.0 or later, just use isActive property of NSLayoutConstraint after creating your IBOutlet.

UPDATED

  • to have strong reference to the outlet per below suggestion, thank you @rob mayoff.
  • to use .isActive instead of .active with Swift 4 per below suggestion, thank you @Mohit Singh.

your cell would have the following outlet:

@IBOutlet var photoBottomConstraint: NSLayoutConstraint! 

and you would access the constraint in willDisplayCell like:

myCell.photoBottomConstraint.isActive = false 

and when you need it again:

myCell.photoBottomConstraint.isActive = true 
like image 72
oyalhi Avatar answered Sep 26 '22 21:09

oyalhi


Base on oyalhi's answer, also want to point out that you have to make a strong reference to your constraints if you want to make it inactive:

@IBOutlet var photoBottomConstraint: NSLayoutConstraint! 

It is not abvious, but if you are using weak reference, photoBottomConstraint could be nil after this call:

myCell.photoBottomConstraint.active = false 
like image 21
Yuchen Avatar answered Sep 26 '22 21:09

Yuchen