iosswiftuikitautolayout

Understanding behaviour of anchors with non-equal constraints


If i create a constraint like this.

contentView.trailingAnchor.constraint(greaterThanOrEqualTo: bubbleImageView.trailingAnchor),

Here is the result, checkout the blue bubble constraint. contentView is the tableview cell and bubbleImageView is the blue bubble. greaterThanEqualToConstraint

Now when i switch to equalTo in the above code constraint here is the result. Check the blue bubbles again. What i don't get is equalTo constraint should behave like greaterThanEqual and vice versa, cause greaterThanEqualTo should expand freely and take up existing space while equalTo should be constraint itself to the text size. equalTo constraint

Here is the github repo if you want to run and check it out incase you don't get the explanation. https://github.com/kodecocodes/alt-materials/tree/editions/1.0/06-self-sizing-views/projects/table-view/final/MessagingApp


Solution

  • You'll find it easier to setup / manage your constraints if you add comments, telling yourself what you want the constraints to do.

    You'll also find it easier (more logical) if you always constrain your bubble view TO the content view, rather than constraining the content view to the bubble view.

    // left-aligned (blue bubble)
    NSLayoutConstraint.activate([
        // leading edge of the bubble should be at the leading edge of the content view
        bubbleImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
        // trailing edge of the bubble should NOT extend past the trailing edge of the content view
        bubbleImageView.trailingAnchor.constraint(lessThanOrEqualTo: contentView.trailingAnchor),
    ])
    
    // right-aligned (green bubble)
    NSLayoutConstraint.activate([
        // trailing edge of the bubble should be at the trailing edge of the content view
        bubbleImageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
        // leading edge of the bubble should NOT extend past the leading edge of the content view
        bubbleImageView.leadingAnchor.constraint(greaterThanOrEqualTo: contentView.leadingAnchor),
    ])