2

Project's Github repository.

So for example, I change this:

let orangeViewCenterXConstraint = NSLayoutConstraint(
  item: orangeView,
  attribute: .centerX,
  relatedBy: .equal,
  toItem: view,
  attribute: .centerX,
  multiplier: 1.0,
  constant: 0.0
)

For this:

orangeView.centerXAnchor.constraint(equalTo: view.centerXAnchor)

How is the proper way to do the same with:

let purpleViewBottomSpaceConstraint = NSLayoutConstraint(
  item: purpleView,
  attribute: .bottom,
  relatedBy: .equal,
  toItem: orangeView,
  attribute: .top,
  multiplier: 1.0,
  constant: -8.0
)

I tried with:

purpleView.bottomAnchor.constraint(equalTo: <#T##NSLayoutAnchor<AnyObject>#>, constant: <#T##CGFloat#>)

But I think purpleView needs a space between purpleView and orangeView, so technically equalTo: orangeView, constant: -8.0, but this is wrong.

I'm not sure of what I'm currently doing, so I'm here to learn.

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59

1 Answers1

1

You have to specify the topAnchor, e.g.:

NSLayoutConstraint.activate([
    purpleView.bottomAnchor.constraint(equalTo: orangeView.topAnchor, constant: -8)
])
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • Thanks!, in xcode8 is: `purpleView.bottomAnchor.constraint(equalTo: orangeView.topAnchor, constant: -8)` – Diego Collao Jun 24 '16 at 03:09
  • Yep, in Xcode 8, that's the new syntax. Updated answer accordingly. – Rob Jun 24 '16 at 03:14
  • I've another question: `let purpleViewTopSpaceConstraint = NSLayoutConstraint(item: purpleView, attribute: .top, relatedBy: .equal, toItem: self.topLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 8.0)` – Diego Collao Jun 24 '16 at 03:16
  • Solved: `purpleView.topAnchor.constraint(equalTo:self.topLayoutGuide.bottomAnchor, constant: 8.0)])` – Diego Collao Jun 24 '16 at 03:37
  • 1
    Correct. You want `topLayoutGuide` if you want that top margin. – Rob Jun 24 '16 at 03:39