5

I am trying to create a constraint via code:

constraintImageCharacterTop = NSLayoutConstraint (item: image,
        attribute: NSLayoutAttribute.Top,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self.view,
        attribute: NSLayoutAttribute.Top,
        multiplier: 1,
        constant: viewTop)
    self.view.addConstraint(constraintImageCharacterTop)

However, I am not sure which is the right NSLayoutAttribute for this constraint. image should have a top space to the main Superview self.view.

This is how I think it works, but I am not sure if I am correct:

Imgur

Should I use NSLayoutAttribute.Top or NSLayoutAttribute.TopMargin for image A?

Cesare
  • 9,139
  • 16
  • 78
  • 130
  • see this thread: http://stackoverflow.com/questions/25807545/what-is-constrain-to-margin-in-storyboard-in-xcode-6 – Jad Feitrouni Feb 01 '15 at 11:01
  • Thank you for your comment! That question explains things a little bit but does not answer my question. – Cesare Feb 01 '15 at 11:02
  • 1
    I usually don't use constraint to margin, it is a personal preference, either to constraint to the edge of the view or to constrain to its margin (8px). Let's say your Image A has a top of 8px, you could create a top constraint with a constant of 8, or a top margin constraint with a constant of 0, you will get the same result. – Jad Feitrouni Feb 01 '15 at 11:30
  • Thank you! So are you saying that creating a top margin constraint of 0px is equal to create a top constraint of 8 px? – Cesare Feb 01 '15 at 11:31
  • Yes, as long as the margins remain 8px – Jad Feitrouni Feb 01 '15 at 11:36
  • Thank you very much. I understand now. Feel free to post your comment as an answer and I'd be glad to accept it. – Cesare Feb 01 '15 at 11:38
  • Thank you, don't hesitate to hit me up if you need more help. – Jad Feitrouni Feb 01 '15 at 11:42

1 Answers1

5

I usually don't use constraint to margin, it is a personal preference, either to constraint to the edge of the view or to constrain to its margin (8px). Let's say your Image A has a top of 8px, you could create a top constraint with a constant of 8, or a top margin constraint with a constant of 0, you will get the same result.

Jad Feitrouni
  • 637
  • 6
  • 12