Order of programmatically created constraints

On Page 133 of Chapter 6, following code is given for adding constraints -

NSLayoutConstraint.activate([ //1

contentView.topAnchor.constraint( equalTo: bubbleImageView.topAnchor, constant: -10),

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

contentView.bottomAnchor.constraint( equalTo: bubbleImageView.bottomAnchor, constant: 10),

contentView.leadingAnchor.constraint( equalTo: bubbleImageView.leadingAnchor, constant: -20),


bubbleImageView.topAnchor.constraint( equalTo: messageLabel.topAnchor, constant: -5),

bubbleImageView.trailingAnchor.constraint( equalTo: messageLabel.trailingAnchor, constant: 10),

bubbleImageView.bottomAnchor.constraint( equalTo: messageLabel.bottomAnchor, constant: 5),

bubbleImageView.leadingAnchor.constraint( equalTo: messageLabel.leadingAnchor, constant: -20)


@jayvenn can u plz explain, how are we deciding that constraints should be from superview to subview(like contentView.topAnchor.constraint( equalTo: bubbleImageView.topAnchor, constant: -10)) and not from subview to superview(like constraint from bubbleImageView to contentView)?

And similar query for the constants values, which we are providing to constants of constraints. Sometimes we are taking it as negative and sometimes as positive. How are we deciding that?


Hi @pulkitap !

You can create a constraint from viewA to viewB or viewB to viewA. Typically, you’d only need to take care of the anchor. If you have:

viewA.trailingAnchor.constraint(equalTo: viewB.leadingAnchor)

Then, you can express the same relationship as:

viewB.leadingAnchor.constraint(equalTo: viewA.trailingAnchor)

The catch here is that both viewA and viewB needs to derive from a common parent view in the view hierarchy.

On the topic of positive or negative constraint constant, this situation depends on the first and second items.

Here’s an example of creating the same layout visually. However, the horizontal spacing constraints differ in the signum.

Positive constraint constant:

Negative constraint constant:

Hope I’ve answered your question! Feel free to ask any clarifying questions.