Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch between two auto-layout constraints?

Tags:

ios

autolayout

I have two UI layout constraints that are conflicting with each other by design. Only one of could be active at a time.

In UIViewController's method updateConstraintsIfNeeded, I have the following code which toggles between the two constraints, depending on the state of a data model.

override func updateConstraintsIfNeeded() {
    super.updateConstraintsIfNeeded()

    if question?.thumbURL != nil {
        showAttachmentConstraint.active = true
        hideAttachmentConstraint.active = false        
    } else {
        showAttachmentConstraint.active = false
        hideAttachmentConstraint.active = true
    }
}

This work as intended, but I got this familiar warning in the debug output:

Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. ...

Apparently when the statement showAttachmentConstraint.active = true is executed, it temporarily conflicts with hideAttachmentConstraint which is still active at that time.

Is it possible to make this toggle operation atomic? I'm hoping there is something like beginUpdate and endUpdate in UITableView.

like image 320
Andree Avatar asked Nov 23 '15 09:11

Andree


People also ask

What are auto layout constraints?

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.

What are two properties that auto layout constraints control on a UIView?

Auto Layout defines margins for each view. These margins describe the preferred spacing between the edge of the view and its subviews. You can access the view's margins using either the layoutMargins or layoutMarginsGuide property.

How do I use Autolayout?

You can add auto layout to a selected frame, component, or component set from a few places: Use the keyboard shortcut ⇧ Shift A . In the right sidebar, click next to Auto layout with a frame selected. Right-click on a frame or object and select Add Auto layout.


1 Answers

you could change the priority of one of the conflicting constraints to 999 instead of 1000. so you do not even have any problems at design time.

like image 112
André Slotta Avatar answered Sep 30 '22 11:09

André Slotta