Diego Collao Diego Collao - 1 year ago 81
Swift Question

change constraints with NSLayoutConstraint

I'm learning autolayout in xcode8 :)! so I'm following the tutorial of teamtreehouse and looks awesome!.

git of the project is here.

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 need a space between purpleView and orangeView, so technically equalTo: orangeView, constant: -8.0, but this is wrong.

I'm not secure of what I'm currently doing, so I'm here to learn :)!,
try to check the github all is commented :)

Thanks :)

Rob Rob

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

    purpleView.bottomAnchor.constraint(equalTo: orangeView.topAnchor, constant: -8)