Search code examples
iosswiftautolayoutsnapkit

Swift: AutoLayout constraints not behaving correctly when device rotates?


I am trying to make constraints for a "chat bubble-esque" view.

My problem is the view doesn't expand to 70% of the device's width, when the device is rotated.

Here is a picture to demonstrate what's going on.

When I rotate the device horizontally, notice on the blue bubble on the right-side device could expand to take up 70% of the space, instead, it keeps its current narrow-width:

enter image description here

Now, here is a picture of what I want to happen. When I rotate the device, can you see that the device on the right actually expands my custom view to 70% of the screen?

enter image description here

What am I doing wrong? How can I achieve the behaviour in the second image?

Here is my code for laying out my custom view using the SnapKit DSL:

bubble.snp.makeConstraints { (make) in
    make.width.lessThanOrEqualToSuperview().multipliedBy(0.7).priority(.required)
    make.top.right.equalToSuperview().inset(20)            
}   

In case you are curious, here is a link to a GitHub Gist of my custom bubble view.

Any help is greatly appreciated!

Edit: My Updated Code:

bubble.snp.makeConstraints { (make) in
    
make.width.lessThanOrEqualToSuperview().multipliedBy(0.7).priority(.required)
    make.width.equalToSuperview().multipliedBy(0.7).priority(.low)
    make.top.right.equalToSuperview().inset(20)
}

Solution

  • You need another constraint that sets the width equal to 0.7 times the width of the superview, but at a lower priority (such as 100). This gives the layout engine something more to aim at when there is ambiguity — and an inequality is always ambiguous.

    enter image description here

    enter image description here

    enter image description here

    enter image description here