0
votes

i'm looking for an explanation of constraint behavoiur, basically i create constraints programatically like this:

leadingConstraint = NSLayoutConstraint(item: yellowBlock, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)

trailingConstraint = NSLayoutConstraint(item: yellowBlock, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0)

(plus top, width and height constraint all set equal to constant but not really relevant). Then i either remove trailing and add leading or vice versa and call UIView animation layoutIfNeeded()

Now what happens the block slides from left to right perfectly (that is final position is aligned to either left or right edge of the screen).

Now i want to add margin on the edges of screen, so i set leading and trailing constraint constant to 10 pp. What happens during animation is the block is perfectly aligned to left margin (10 pp), but once it slides to the right edge it actually goes beyond screen (recon by that 10 pp). Why it goes off screen? If i set leading constraint to 10, and trailing to (minus) -10 then it's all perfect aligned with 10 pp margin on both sides. This makes no sense to me : (

I'm sure there's no other constraints, even tried resetting all constraints like this:

yellowBlock.removeFromSuperview()
yellowBlock.removeConstraints(yellowBlock.constraints())
self.view.addSubview(yellowBlock)
yellowBlock.setTranslatesAutoresizingMaskIntoConstraints(false)

thank you,

1

1 Answers

1
votes

This happens because constraints has directions and don't work as a padding in CSS. If you read the documentation for constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant: You will see that the attr1 is the attribute of the view for the left hand side of the constraint. The attr2 is for the right hand side of the constraint.

So either you need to set one positive and other negative or change the order of the views and attributes.